您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Swift中从笔尖加载UIView

在Swift中从笔尖加载UIView

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
   }
   ...
}

请注意,通过这种方式,我得到了一个从笔尖加载自身的类。然后,只要可以在项目中使用UIView(在界面生成器中或以编程方式),就可以将SomeView用作类。

在以下扩展中加载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 ...
}

信用:在此解决方案中使用通用扩展名的灵感来自以下罗伯特的回答。

将“视图”更改为“ contentView”以避免混淆。还将数组下标更改为“ .first”。

Swift 2022/1/1 18:13:41 有757人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶