程序员

swift xib创建view时实例化

2022-06-17  本文已影响0人  心猿意码_
方式一
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)
方式二
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))
    }
}
let myView = Bundle.loadView(fromNib: "MyClass", withType: MyClass.self)
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")
 }
上一篇下一篇

猜你喜欢

热点阅读