Swift 3 Load xib. NSBundle.mainBundle().loadNibNamed return Bool

孤者浪人 提交于 2019-12-05 04:49:06

First of all the method has not been changed in Swift 3.

loadNibNamed(_:owner:topLevelObjects:) has been introduced in macOS 10.8 and was present in all versions of Swift. However loadNibNamed(nibName:owner:options:) has been dropped in Swift 3.

The signature of the method is

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

so you have to create an pointer to get the array of the views on return.

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
}

Edit: I updated the answer to filter the NSView instance reliably.


In Swift 4 the syntax slightly changed and using first(where is more efficient:

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

Swift 4 version of @vadian's answer

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

I wrote an extension that is safe and makes it easy to load from nib:

extension NSView {
    class func fromNib<T: NSView>() -> T? {
        var viewArray = NSArray()
        guard Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, topLevelObjects: &viewArray) else {
            return nil
        }
        return viewArray.first(where: { $0 is T }) as? T
    }
}

Then just use like this:

let view: CustomView = .fromNib()

Whether CustomView is a NSView subclass and also CustomView.xib.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!