如何在Swift中使用XIB文件初始化/实例化自定义UIView类 [英] How to initialize/instantiate a custom UIView class with a XIB file in Swift
本文介绍了如何在Swift中使用XIB文件初始化/实例化自定义UIView类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为 MyClass
的类,它是 UIView
的子类,我想用<初始化 XIB
文件。我不知道如何使用名为 View.xib的xib文件初始化此类
I have a class called MyClass
which is a subclass of UIView
, that I want to initialize with a XIB
file. I am not sure how to initialize this class with the xib file called View.xib
class MyClass: UIView {
// what should I do here?
//init(coder aDecoder: NSCoder) {} ??
}
推荐答案
我测试了这段代码吧效果很好
I tested this code and it works great
class MyClass: UIView {
class func instanceFromNib() -> UIView {
return UINib(nibName: "nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView
}
}
初始化视图并使用如下所示
Initialise the view and use it like below
var view = MyClass.instanceFromNib()
self.view.addSubview(view)
OR
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
}
这篇关于如何在Swift中使用XIB文件初始化/实例化自定义UIView类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文