简体   繁体   English

如何子类化UIViewController并快速添加属性?

[英]How to subclass a UIViewController and add properties in swift?

I want to make a new kind of view controller in Swift that has an additional property that must be explicitly initialized. 我想在Swift中创建一种新型的视图控制器,该控制器具有必须显式初始化的其他属性。 It doesn't make any sense for this property to be nil or have a default value and the controller will only be initialized programmatically. 该属性为nil或具有默认值没有任何意义,并且该控制器将仅通过编程方式进行初始化。 I tried defining it like this: 我试图这样定义它:

class MyController : UIViewController {
  var prop: Int
  init(prop: Int) {
    self.prop = prop
    super.init()
  }

  required init(coder aDecoder: NSCoder?) {
    fatalError("don't serialize this")
  }
}

I tried running this but it crashed because super.init() tries to run the nib constructor which isn't defined, so I tried adding that: 我尝试运行此程序,但由于super.init()尝试运行未定义的nib构造函数而导致崩溃,因此我尝试添加该函数:

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

But now the compiler complains that prop isn't being initialized. 但是现在编译器抱怨prop没有被初始化。 And this is my question: how can I initialize prop correctly here? 这是我的问题: 如何在此处正确初始化prop I don't want a default value, and anything I set will override the correct value that I set in the other initializer. 我不需要默认值,并且我设置的任何内容都将覆盖在其他初始化程序中设置的正确值。

I kinda hacked around it by setting some default value in the nib init, but then having my first init do this 我通过在笔尖初始化中设置一些默认值来破解它,但是随后让我的第一个初始化执行此操作

self.prop = prop
super.init()
self.prop = prop

But other than being really weird and ugly, that makes me worried that now it is possible to initialize my view controller from a nib and end up with the default value, which would be bad. 但是除了真正的怪异和丑陋之外,这令我担心,现在可以从笔尖初始化视图控制器并最终得到默认值了,这很糟糕。

What is the correct and idiomatic way to do this in Swift? 在Swift中执行此操作的正确且惯用的方法是什么?

At some point the view controller must be initialized by calling init(nibName:bundle:) or init(coder:) 在某个时候,必须通过调用init(nibName:bundle:)init(coder:)初始化视图控制器。

Try this: 尝试这个:

class MyViewController: UIViewController {

    var prop: Int

    init(prop: Int, nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) {
        self.prop = prop
        super.init(nibName:nibNameOrNil, bundle: nibBundleOrNil)
    }

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

}

Try the following 尝试以下

class MyController: UIViewController {

    var prop: Int

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }

    init(prop: Int) {
        self.prop = prop
        super.init(nibName: nil, bundle: nil)
    }
}

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

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