简体   繁体   中英

How to write custom UIViewController initialiser with property in Swift?

I am trying to write my own UIVC initializer:

let person: Person

    init(withPerson person: Person) {
        self.person = person
        super.init()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

but in my coordinator I have this line:

func getViewController() -> UIViewController? {
        return ViewController(nibName: "ViewController", bundle: Bundle.main)
    }

and it causes a crash with error:

 Fatal error: Use of unimplemented initializer 'init(nibName:bundle:)' for class 'ViewController'

when I try to add:

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

it rises an error with:

Property 'self.person' not initialized at super.init call

is there a way how I can fix the crash?

init(withPerson person: Person) {
    self.person = person
    super.init (nibName: "ViewController", bundle: Bundle.main)
}

You have to call super.init(nibName:bundle:) instead of super.init() as it's a designated initializer.

If you specify nil for the nibName parameter and you do not override the loadView() method, the view controller searches for a nib file as described here .

init(withPerson person: Person) {
    self.person = person
    super.init(nibName: nil, bundle: nil)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM