加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

可可 – Swift 3加载xib. NSBundle.mainBundle().loadNibNamed返

发布时间:2020-12-14 05:22:50 所属栏目:百科 来源:网络整理
导读:我试图弄清楚如何使用xib文件创建自定义视图. 在此 question中,使用下一个方法. NSBundle.mainBundle().loadNibNamed("CardView",owner: nil,options: nil)[0] as! UIView Cocoa具有相同的方法,但是,这个方法在swift 3到loadNibNamed(_:owner:topLevelObject
我试图弄清楚如何使用xib文件创建自定义视图.
在此 question中,使用下一个方法.
NSBundle.mainBundle().loadNibNamed("CardView",owner: nil,options: nil)[0] as! UIView

Cocoa具有相同的方法,但是,这个方法在swift 3到loadNibNamed(_:owner:topLevelObjects:)中已经改变,它返回Bool,并且之前的代码生成“Type Bool没有下标成员”错误,这很明显,因为返回类型是Bool.

所以,我的问题是如何从Swift 3中的xib文件加载视图

首先,Swift 3中没有改变该方法.

loadNibNamed(_:owner:topLevelObjects :)已经在macOS 10.8中引入,并且存在于所有版本的Swift中.但是,在Swift 3中删除了loadNibNamed(nibName:owner:options :).

该方法的签名是

func loadNibNamed(_ nibName: String,owner: Any?,topLevelObjects: AutoreleasingUnsafeMutablePointer<NSArray>?) -> Bool

所以你必须创建一个指针来获取返回的视图数组.

var topLevelObjects = NSArray()
if Bundle.main.loadNibNamed("CardView",owner: self,topLevelObjects: &topLevelObjects) {
   let views = (topLevelObjects as Array).filter { $0 is NSView }
   return views[0] as! NSView
}

编辑:我更新了答案,可靠地过滤NSView实例.

在Swift 4中,语法略有改变并首先使用(其中效率更高:

var topLevelObjects : NSArray?
if Bundle.main.loadNibNamed(assistantNib,topLevelObjects: &topLevelObjects) {
     return topLevelObjects!.first(where: { $0 is NSView }) as? NSView
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读