user12345 user12345 - 3 months ago 6
Swift Question

How to init a UIViewController whose Nib is the Storybaord

I have the following

UIViewController
:

class ViewController: UIViewController{

var dayDatasource : DayDatasource;

init(){
self.dayDatasource = DayDatasource();
super.init(nibName:nil, bundle: nil);
}

required init?(coder aDecoder: NSCoder) {
self.dayDatasource = DayDatasource();
super.init(nibName:nil, bundle: nil);
}

override func viewDidLoad() {
super.viewDidLoad();
}
}


Now because I declare the
dayDatasource
property, swift forces me to create
init
methods. When I create the
init
methods it then complains that I need to call the designated
init
method for
UIViewController
. After googling, apparently the designated `init method is:

super.init(nibName:nil, bundle: nil);


When I use this however, I get a back screen. If I try the following:

super.init(nibName:"ViewController", bundle: NSBundle.mainBundle());


I get the following error:


Could not load NIB in bundle: 'NSBundle'


What should I do in this situation?

Answer

If you're using storyboard segues for navigation, you should make dayDatasource an optional or forced unwrapped optional with a ? or !. That will prevent requiring you to create the unused init method.

Then, in the view controller you are navigating from, override the func prepare(for segue: UIStoryboardSegue, sender: Any?) function and set the dayDatasource variable.

On the other hand, if this is the first view controller being displayed, or you always want a new instance of dayDatasource, just create the instance in your variable declaration and the custom init will no longer be required.

var dayDatasource = DayDatasource()
Comments