一直很混淆这种用法,这里记录下来并分享给小白童鞋们
1. 新建DemoView.swift 和 DemoView.xib

2. 设置xib文件的file's onwer选项

3. 绑定xib中的控件到swift文件中


4. 在swift文件中实现从xib的初始化加载
// 定义container为DemoView的子view, 以便更方便的封装xib
private var container: UIView!
// 从storyboard上初始化时,会调用该方法
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
private func xibSetup() {
container = Bundle.main.loadNibNamed("DemoView", owner: self, options: nil)?.first as! UIView
container.frame = bounds
container.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(container)
}
5. 在storyboard上使用

这样,基本上写很少的代码,就能实现xib自定义view在任何地方的使用

网友评论