在 Swift 中将 xib 分配给 UIView [英] Assign xib to the UIView in Swift
本文介绍了在 Swift 中将 xib 分配给 UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在objective c中,它可以在init方法中通过
in objective c it can be done in init method by
-(id)init{
self = [[[NSBundle mainBundle] loadNibNamed:@"ViewBtnWishList" owner:0 options:nil] objectAtIndex:0];
return self;
}
但是当我快速执行此操作时
but when i do this in swift
init(frame: CGRect) {
self = NSBundle.mainBundle().loadNibNamed("ViewDetailMenu", owner: 0, options: nil)[0] as? UIView
}
cannot assignment to self in a method 显示错误.现在我的方法是创建一个视图,并将从 nib 加载的视图添加到它.有人有更好的主意吗?
cannot assign to self in a method error is shown. now my approach is to create a view, and add the view loaded from nib to it. anyone have a better idea?
推荐答案
for Swift 4
extension UIView {
class func loadFromNibNamed(nibNamed: String, bundle: Bundle? = nil) -> UIView? {
return UINib(
nibName: nibNamed,
bundle: bundle
).instantiate(withOwner: nil, options: nil)[0] as? UIView
}
}
适用于 Swift 3
你可以在 UIView 上创建一个扩展:
You could create an extension on UIView:
extension UIView {
class func loadFromNibNamed(nibNamed: String, bundle: NSBundle? = nil) -> UIView? {
return UINib(
nibName: nibNamed,
bundle: bundle
).instantiateWithOwner(nil, options: nil)[0] as? UIView
}
}
注意:使用 UINIb 速度更快,因为它会为您缓存.
Note: Using UINib is faster because it does caching for you.
然后你可以这样做:
ViewDetailItem.loadFromNibNamed("ViewBtnWishList")
并且您将能够在任何视图上重复使用该方法.
And you will be able to reuse that method on any view.
这篇关于在 Swift 中将 xib 分配给 UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文