我有一个称为MyClass的子类UIView,我想用一个XIB文件初始化。我不确定如何使用名为xib的文件初始化此类View.xib
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 } }
初始化视图并按如下方式使用它:
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 }