小编典典

如何在Swift中使用XIB文件初始化/实例化自定义UIView类

swift

我有一个称为MyClass的子类UIView,我想用一个XIB文件初始化。我不确定如何使用名为xib的文件初始化此类View.xib

class MyClass: UIView {

    // what should I do here? 
    //init(coder aDecoder: NSCoder) {} ?? 
}

阅读 651

收藏
2020-07-07

共1个答案

小编典典

我测试了这段代码,它很好用:

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
}
2020-07-07