Swift 3加载xib.NSBundle.mainBundle().loadNibNamed返回Bool

Ale*_*xei 7 cocoa xib nsview nib swift3

我试图弄清楚如何使用xib文件创建自定义视图.在这个问题中,使用了下一个方法.

NSBundle.mainBundle().loadNibNamed("CardView", owner: nil, options: nil)[0] as! UIView
Run Code Online (Sandbox Code Playgroud)

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

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

vad*_*ian 9

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

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

该方法的签名是

func loadNibNamed(_ nibName: String, 
                      owner: Any?, 
            topLevelObjects: AutoreleasingUnsafeMutablePointer<NSArray>?) -> Bool
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

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


Swift 4中,语法略有改变,使用first(where效率更高:

var topLevelObjects : NSArray?
if Bundle.main.loadNibNamed(assistantNib, owner: self, topLevelObjects: &topLevelObjects) {
     return topLevelObjects!.first(where: { $0 is NSView }) as? NSView
}
Run Code Online (Sandbox Code Playgroud)


Rya*_*n H 5

Swift 4版@vadian的答案

var topLevelObjects: NSArray?
if Bundle.main.loadNibNamed(NSNib.Name(rawValue: nibName), owner: self, topLevelObjects: &topLevelObjects) {
    return topLevelObjects?.first(where: { $0 is NSView } ) as? NSView
}
Run Code Online (Sandbox Code Playgroud)