我有一个名为 MyClass
的类,它是 UIView
的子类,我想用一个 XIB
文件对其进行初始化。我不确定如何使用名为 View.xib
class MyClass: UIView {
// what should I do here?
//init(coder aDecoder: NSCoder) {} ??
}
最佳答案
我测试了这段代码,它运行良好:
class MyClass: UIView {
class func instanceFromNib() -> UIView {
return UINib(nibName: "nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView
}
}
初始化 View 并像下面这样使用它:
var view = MyClass.instanceFromNib()
self.view.addSubview(view)
或
var view = MyClass.instanceFromNib
self.view.addSubview(view())
更新 Swift >=3.x & Swift >=4.x
class func instanceFromNib() -> UIView {
return UINib(nibName: "nib file name", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
}
关于ios - 如何在 Swift 中使用 XIB 文件初始化/实例化自定义 UIView 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25513271/