swift xib创建view时实例化
2022-06-17 本文已影响0人
心猿意码_
方式一
- Xib 自定义View实例化
class MyClass: UIView {
class func instanceFromNib() -> UIView {
return UINib(nibName:"nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView
}
}
- 使用
var view = MyClass.instanceFromNib()
view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
self.view.addSubview(view)
方式二
- 创建Bundle的通用方法
extension Bundle {
static func loadView<T>(fromNib name: String, withType type: T.Type) -> T {
if let view = Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as? T {
return view
}
fatalError("Could not load view with type " + String(describing: type))
}
}
- 使用方式1
let myView = Bundle.loadView(fromNib: "MyClass", withType: MyClass.self)
- 使用方式2
class MyClass: UIView {
class func loadView() -> UIView {
return Bundle.loadView(fromNib: "MyClass", withType: MyClass.self)
}
}
var view = MyClass.loadView()
view.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
self.view.addSubview(view)
注意:
MyClass.swift 文件中重写
required init?(coder:NSCoder) {
super.init(coder: coder)
}
如下方式重写会报错: Thread 1: Fatal error: init(coder:) has not been implemented
required init?(coder:NSCoder) {
fatalError("init(coder:) has not been implemented")
}