Swift: Custom ViewController initializers

BadmintonCat picture BadmintonCat · Aug 27, 2014 · Viewed 59.4k times · Source

How do you add custom initializers to UIViewController subclasses in Swift?

I've created a sub class of UIViewController that looks something like this:

class MyViewController : UIViewController
{
    init(leftVC:UIViewController, rightVC:UIViewController, gap:Int)
    {
        self.leftVC = leftVC;
        self.rightVC = rightVC;
        self.gap = gap;

        super.init();

        setupScrollView();
        setupViewControllers();
    }
}

When I run it I get a fatal error:

fatal error: use of unimplemented initializer 'init(nibName:bundle:)' for class 'MyApp.MyViewController'

I've read elewhere that when adding a custom initializer one has to also override init(coder aDecoder:NSCoder) so let's override that init and see what happens:

override init(coder aDecoder: NSCoder)
{
    super.init(coder: aDecoder);
}

If I add this, Xcode complains that self.leftVC is not initialized at super.init call. So I guess that can't be the solution either. So I wonder how can I add custom initializers properly to a ViewController subclass in Swift (since in Objective-C this seems not to be a problem)?

Answer

BadmintonCat picture BadmintonCat · Aug 27, 2014

Solved it! One has to call the designated initializer which in this case is the init with nibName, obviously ...

init(leftVC:UIViewController, rightVC:UIViewController, gap:Int)
{
    self.leftVC = leftVC
    self.rightVC = rightVC
    self.gap = gap

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

    setupScrollView()
    setupViewControllers()
}