【问题标题】:How do I create the init for a UIViewController subclass that I create programmatically in Swift?如何为我在 Swift 中以编程方式创建的 UIViewController 子类创建 init?
【发布时间】:2014-06-30 18:45:59
【问题描述】:

假设我的UIViewController 有两个属性,var animal: Stringvar color: UIColor

如何创建自定义init,以便我可以轻松地在代码中创建它?

我想拥有:

init(animal: String, color: UIColor) {
   self.animal = animal
   self.color = color
}

但是我得到一个编译器错误,我没有使用指定的初始化程序。我做错了什么/我应该怎么做?

【问题讨论】:

    标签: ios cocoa-touch uiviewcontroller swift ios8


    【解决方案1】:

    设置这些属性后调用super.init()。这应该够了吧。您的方法应如下所示:

    init(animal: String, color: UIColor) {
       self.animal = animal
       self.color = color
       super.init()
    }
    

    【讨论】:

    • 通常在 Swift 中,super.init 应该被最后调用。
    • super.init() 不是 UIViewController 的指定初始化器
    猜你喜欢
    • 1970-01-01
    • 2015-07-27
    • 2015-01-24
    • 2011-02-10
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    相关资源
    最近更新 更多