I’m adding an NSViewController
subclass to a library and trying to have my cake and eat it too.
The default implementation of MyViewController() ( Or init() ) throws an exception
if it can’t find itself in a nib or storyboard. In order to overcome this I must override loadView()
and create and assign a view in code. What I really want to do is both, create a view in the code, but only have that code run in the event that the super’s implementation doesn’t find one in a nib. I tried a
do {
super.loadView()
}
catch{
//viewCreatingCode
}
But unfortunately loadView is not marked as throws so the catch doesn’t work. Any ideas?
Ok, here's what you're going to want to do.
NSViewController
has three properties you want to inspect: nibBundle
, nibName
, and storyboard
. All three of these properties are optional, and they're set before loadView
is called.
The default implementation of loadView
checks to see if these properties are set. If so, it'll initialize the view from that nib or storyboard. Otherwise, it creates an empty NSView
.
In your implementation of loadView
, you'll want to check these values too. If nibName
and storyboard
are both nil
, you can create and set up the view how you'd like.
override func loadView() {
guard nibName == nil, storyboard == nil else {
super.loadView()
return
}
view = MyCustomView()
}