I am converting my Objective-C code to Swift and was wondering what is the swift equivalent to this code
[[[NSBundle mainBundle] loadNibNamed:@"Games-New" owner:nil
options:nil] firstObject];
Thanks.
Maybe the API has changed. The third parameter of loadNibNamed
is no longer options
, it's topLevelObjects
. The following code works for me:
var objects: NSArray?
NSBundle.mainBundle().loadNibNamed("MyView", owner: self, topLevelObjects: &objects)
NSBundle.mainBundle().loadNibNamed("Games-New", owner: nil, options: nil)[0]
Here is a UIView extension
public extension UIView {
public class func instantiateFromNib<T: UIView>(viewType: T.Type) -> T {
return NSBundle.mainBundle().loadNibNamed(String(describing: viewType), owner: nil, options: nil)?.first as! T
}
public class func instantiateFromNib() -> Self {
return instantiateFromNib(self)
}
}
Usage
let awesomeView = AwesomeView.instantiateFromNib()
OR
let awesomeView = UIView.instantiateFromNib(AwesomeView.self)
Swift 3
owner
The object to assign as the nib’s File's Owner object.
options
A dictionary containing the options to use when opening the nib file.
first
if you do not define first then grabing all view .. so you need to grab one view inside that set frist
.
Bundle.main.loadNibNamed("yourUIView", owner: self, options: nil)?.first as! yourUIView
Use this to load your nib.
let myView = NSBundle.mainBundle().loadNibNamed("MyView", owner: nil, options: nil)[0] as UIView
Then you can add it to your view as you normally would.
view.addSubview(myView)
For Swift 3:
Bundle.main.loadNibNamed("Games-New", owner: nil, options: nil)?[0]
FYI: NS is (not entirely) removed in Swift 3
In the docs, it looks like it is different for macOS and iOS.
For macOS and Swift 4, the following worked for me:
func loadFromNib(_ nibName: String) -> NSView? {
var topLevelObjects: NSArray?
if Bundle.main.loadNibNamed(NSNib.Name(rawValue: nibName), owner: self, topLevelObjects: &topLevelObjects) {
return topLevelObjects?.first(where: { $0 is NSView } ) as? NSView
} else {
return nil
}
}
in Swift 4, NSBundle.mainBundle changed to Bundle.main.loadNibNamed
Bundle.main.loadNibNamed("MyDenizbankLoading", owner: nil, options: nil)![0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With