简体   繁体   English

用 Swift 初始化 UIViewController 的子类?

[英]Initialize a subclass of UIViewController with Swift?

I'm trying to understand how initialization works in Swift with a subclass of a UIViewController.我试图通过 UIViewController 的子类了解 Swift 中的初始化是如何工作的。 I thought the basic format was this, but it is throwing errors...我认为基本格式是这样的,但它抛出错误......

init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)   {
    //other code
    super.init(nibName: String?, bundle: NSBundle?)
}

You're passing the types, not the variables.您传递的是类型,而不是变量。 You have to pass the variables instead.您必须改为传递变量。

init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)  {
    // Initialize variables.

    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}

Variables should now be initialized before the call to super.init现在应该在调用 super.init 之前初始化变量

init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)  {

    // Initialize variables.

    super.init() // as required
}

You can initialize with/without parameters.您可以使用/不使用参数进行初始化。

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

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

// Initialize with value
init(_ sender: Any?) {
    super.init(nibName: nil, bundle: nil)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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