I recently upgraded my project to Swift and I'm trying to figure out how to instantiate my XIBs dynamically while maintaining strong references to my viewcontrollers. I hate having to call NSBundle.mainBundle().loadNibNamed("someXib")
because having a string-representation of your viewcontroller can make it prone to typos, hard to remember what each XIB is named, and very difficult to rename a XIB if I so choose.
In objective-c, I would simply instantiate the viewcontroller and push it like so:
CRMyViewController *myVC = [CRMyViewController new];
[self.navigationController presentViewController:myVC animated:YES completion:nil];
This allows me to strongly-reference my viewcontrollers (and their associated XIB) and if I misspelled or renamed my viewcontroller, my project would simply not compile.
When I tried this approach referencing a Swift-XIB, my view never loaded. However I was able to get close to what I wanted by simply overriding loadView inside my viewcontroler:
override func loadView() {
NSBundle.mainBundle().loadNibNamed("CRMyViewController", owner:self, options:nil)
}
This is close to what I want since I only hard-code the xib name once (and inside the actual viewcontroller) but I'd still prefer a more dynamic approach.
Is there any way to load the Swift-XIB along with the viewcontroller dynamically? The only thing I can think of is to create my own base viewcontroller and override the loadView in a more dynamic fashion:
override func loadView() {
var className:NSString = NSStringFromClass(self.classForCoder)
className = className.componentsSeparatedByString(".").last as NSString
NSBundle.mainBundle().loadNibNamed(className, owner:self, options:nil)
}
Is there a better approach to load the XIB along with the viewcontroller? How come this is necessary in Swift and not objective-c?