简体   繁体   English

如何使用 Swift 中的属性编写自定义 UIViewController 初始化程序?

[英]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.

相关问题 如何在Swift中实现uiviewController的自定义初始化方法 - How to implement custom initialiser method of uiviewController in swift Swift中,如何复用UIVIewController中的一个属性 - In Swift, how to reuse a property in a UIVIewController 如何在 Swift 中编写 UIViewController 的 init 方法 - How to write init methods of a UIViewController in Swift 如何在自定义uiview中调用UIViewController属性? - How to call a UIViewController property in custom uiview? 在Swift中为UIViewController定制UIView - Custom UIView for an UIViewController in Swift 自定义UIViewController在Swift中使用animateWithDuration进行转换 - Custom UIViewController transitions with animateWithDuration in Swift 如何使用协议关闭和显示自定义弹出窗口(UIViewController)-SWIFT - How to dismiss and present a custom popup (UIViewController) using protocols - SWIFT Swift如何使用自定义UITableView类将UITableView添加到UIViewController - Swift how to add UITableView to UIViewController with custom UITableView class 如何在Swift 4中从自定义类导航到UIViewController - How can I navigate from custom class to UIViewController in Swift 4 如何比较Swift 3中的UIViewController? - How to compare UIViewController in Swift 3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM