How to write init methods of a UIViewController in Swift

前端 未结 8 1553
长发绾君心
长发绾君心 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 17:58

    I was facing the same issue with Swift 5 in Xcode 12.0 and this is my solution in 2020.

    class Foo: UIViewController {
        private var bar: Bar!
    
        override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
            super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    
            setupController()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
            setupController()
        }
        
        private func setupController() {
            bar = Bar()
        }
    }
    

    and an alternative I am using is to do the initialization inside loadView function.

    class Foo: UIViewController {
        private var bar: Bar!
        
        override func loadView() {
            setupController()
        }
    
        private func setupController() {
            bar = Bar()
        }
    }
    

提交回复
热议问题