将xib指定给Swift中的UIView

前端之家收集整理的这篇文章主要介绍了将xib指定给Swift中的UIView前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在目标c中它可以在init方法中完成
  1. -(id)init{
  2. self = [[[NSBundle mainBundle] loadNibNamed:@"ViewBtnWishList" owner:0 options:nil] objectAtIndex:0];
  3. return self;
  4. }

但当我在swift中这样做

  1. init(frame: CGRect) {
  2. self = NSBundle.mainBundle().loadNibNamed("ViewDetailMenu",owner: 0,options: nil)[0] as? UIView
  3. }

不能分配给自己在方法显示错误
现在我的方法是创建一个视图,并将从nib加载的视图添加到它。
任何人都有一个更好的主意?

您可以在UIView上创建扩展:
  1. extension UIView {
  2. class func loadFromNibNamed(nibNamed: String,bundle : NSBundle? = nil) -> UIView? {
  3. return UINib(
  4. nibName: nibNamed,bundle: bundle
  5. ).instantiateWithOwner(nil,options: nil)[0] as? UIView
  6. }
  7. }

注意:使用UINib更快,因为它为您缓存。

然后你可以做:

  1. ViewDetailItem.loadFromNibNamed("ViewBtnWishList")

您将能够在任何视图上重用该方法

猜你在找的Swift相关文章