I am unable to add init method to the following UIViewController class. I need to write some code in the init method. Do i have to write init(coder) method? Even when I add
You need to override the init(nibName:bundle:)
initializer, and provide the init(coder:)
required initializer, and initialize tap
in both of them:
class ViewController: UIViewController {
var tap: UITapGestureRecognizer?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
print("init nibName style")
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
}
// note slightly new syntax for 2017
required init?(coder aDecoder: NSCoder) {
print("init coder style")
super.init(coder: aDecoder)
tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
}
...
...
}
Also, be sure when calling the superclass initializer that you don't just pass nil
for the nibName
and bundle
. You should pass up whatever was passed in.
Note that the "convenience init" method mentioned in some answers is only relevant if you are actually "by hand" yourself initializing a view controller. (There are very few situations where you would do that.) If you want to "do something during normal initialization" - so for example create a gesture recognizer or just initialize some variables - the only possible solution is exactly the one given in this answer.