如何创建一个视图然后关联一个XIB

列举了一种使用File’s Owner关联视图的方法,仅供参考

part 1

创建一个视图,创建一个XIB文件

part 2

在xib文件的File’s Owner设置所有者为当前视图




part 3 声明私有方法.

// MARK: - Private
private func nibName() -> String {
return        self.dynamicType.description().componentsSeparatedByString(".").last!
  }

part 4 在loadViewFromNib内添加xib视图

func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName(), bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(view);
return view
  }

part 5 在初始化方法内调用loadViewFromNib方法

  // MARK: - init
  override init(frame: CGRect) {
super.init(frame: frame)
view = loadViewFromNib()
  }

  required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
view = loadViewFromNib()
  }