这是我的Objective-C代码,我正在使用它为我的定制UIView
加载nib:
-(id)init{
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"myXib" owner:self options:nil];
return [subviewArray objectAtIndex:0];
}
Swift中的等效代码是什么?
这是我的Objective-C代码,我正在使用它为我的定制UIView
加载nib:
-(id)init{
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"myXib" owner:self options:nil];
return [subviewArray objectAtIndex:0];
}
Swift中的等效代码是什么?
Original Solution
.
class SomeView: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSBundle.mainBundle().loadNibNamed("SomeView", owner: self, options: nil)
self.addSubview(self.view); // adding the top level view to the view hierarchy
}
...
}
注意,通过这种方式,我得到了一个从nib加载自己的类.然后,只要UIView可以在项目中使用(在interface builder中或以编程方式使用),我就可以使用SomeView作为一个类.
Update - using Swift 3 syntax
在以下扩展中加载xib是作为一个实例方法编写的,然后可以由上面的初始化器使用:
extension UIView {
@discardableResult // 1
func fromNib<T : UIView>() -> T? { // 2
guard let contentView = Bundle(for: type(of: self)).loadNibNamed(String(describing: type(of: self)), owner: self, options: nil)?.first as? T else { // 3
// xib not loaded, or its top view is of the wrong type
return nil
}
self.addSubview(contentView) // 4
contentView.translatesAutoresizingMaskIntoConstraints = false // 5
contentView.layoutAttachAll(to: self) // 6
return contentView // 7
}
}
调用方方法可能如下所示:
final class SomeView: UIView { // 1.
required init?(coder aDecoder: NSCoder) { // 2 - storyboard initializer
super.init(coder: aDecoder)
fromNib() // 5.
}
init() { // 3 - programmatic initializer
super.init(frame: CGRect.zero) // 4.
fromNib() // 6.
}
// other methods ...
}
信用:在这个解决方案中使用一个通用的扩展是受Robert下面的答案启发的.
Edit