[英]How to write custom UIViewController initialiser with property in Swift?
I am trying to write my own UIVC initializer:我正在尝试编写自己的 UIVC 初始化程序:
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.您必须调用
super.init(nibName:bundle:)
而不是super.init()
因为它是指定的初始化程序。
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 .如果您为 nibName 参数指定 nil 并且您不覆盖 loadView() 方法,则视图 controller 将按照此处所述搜索 nib 文件。
init(withPerson person: Person) {
self.person = person
super.init(nibName: nil, bundle: nil)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.