How to write init methods of a UIViewController in Swift

前端 未结 8 1569
长发绾君心
长发绾君心 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:03

    I came across this Question of You asked long way Back. But no one has provided a basic answer to the question. It's a basic in Swift that:- Subclass must initialize its variables before it's super class initialization is complete.

    Hence as Ankit Goel mentioned the crash :- "Must call a designated initializer of superclass"

    Hence updated code would be:-

    class ViewController: UIViewController {
     var tap: UITapGestureRecognizer?
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)   {
    print("init nibName style")
    self.tap = nil
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    self.tap = UITapGestureRecognizer(target: self, action: Selector(("handleTap:")))
    }
    
    required init?(coder aDecoder: NSCoder) {
    print("init coder style")
    self.tap = nil
    super.init(coder: aDecoder)
    tap = UITapGestureRecognizer(target: self, action: Selector(("handleTap:")))
     }}
    

提交回复
热议问题