我有一个类叫MyClass是UIView的子类,我想用xib文件初始化。我不知道如何用名为View.xib的xib文件初始化这个类
class MyClass: UIView{ //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())
UDATE Swift 3.x
class func instanceFromNib() -> UIView { return UINib(nibName: "nib file name",bundle: nil).instantiate(withOwner: nil,options: nil)[0] as! UIView }