Some developers prefer to keep ViewControllers design in separate XIB files instead of placing everything in Storyboard. Especially on displays with the smaller real estate (like working on a MacBook), navigating and editing the storyboard could be tedious.
There is a simple technique which lets us keep storyboard ViewControllers and segues between. Following one of the tutorials available is simple:
- Place UIViewController on storyboard
- Highlight its View and delete it. You should now have “hollow” ViewController.
- In identity inspector, set the custom class to name of your choice.
- Click File -> New, create new Cocoa Touch subclass of UIViewController. Don’t forget to check “Also create XIB file“. Name the class exactly as on Storyboard.
It works perfectly with Objective-C projects – iOS takes care of loading view from XIB, provided it has the exactly same name as the class. But if the class is written in Swift, all you get is black screen.
Fixing on Swift side
Apparently this smart mechanism is broken newest Xcode builds (including GM). Fortunately, simple remedies exist.
Name the XIB
Just change name of XIB file to ModuleName.ClassName.xib and view should be loaded.
Load XIB programmatically
If renaming XIBs is not appealing to you, you may keep XIB name as it is, and override loadView: method with short snippet of code:
1 2 3 |
override func loadView() { NSBundle.mainBundle().loadNibNamed("ViewController", owner: self, options: nil) } |
November 2016 Update
In Xcode 8.x/Swift 3.x naming the XIB in smart way seems to not to work anymore. Still there is programmatic way, which may be preferred as more explicit. In Swift 3, loading code would look slightly different, because of different conventions of mapping Foundation classes to Swift:
1 2 3 |
override func loadView() { Bundle.main().loadNibNamed("ViewController", owner: self, options: nil) } |
loadView is responsible for creating ViewController’s view. Override it to get control over view creation process.