How to write init methods of a UIViewController in Swift

前端 未结 8 1552
长发绾君心
长发绾君心 2020-12-07 17:14

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

8条回答
  •  攒了一身酷
    2020-12-07 18:10

    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.

提交回复
热议问题