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)?
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
If you subclass from something and need to create a new init , or override an existing init , Xcode will create an error telling you need also need to include required init?(coder aDecoder: NSCoder) . The decoder, NSCoder is related to the the Interface Builder.
The UIViewController class defines the shared behavior that's common to all view controllers. You rarely create instances of the UIViewController class directly. Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller's view hierarchy.
Override initializer In Swift initializers are not inherited for subclasses by default. If you want to provide the same initializer for a subclass that the parent class already has, you have to use the override keyword.
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() }
For a more generic UIViewController you can use this as of Swift 2.0
init() { super.init(nibName: nil, bundle: nil) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With