【问题标题】:required init?(coder aDecoder: NSCoder) not called必需的 init?(coder aDecoder: NSCoder) 未调用
【发布时间】:2016-09-22 08:23:43
【问题描述】:

我编写了自己的 Button、Textfield、...、类。在“自定义类”的情节提要中,我将类设置为 UIElement。这很好用。

现在我需要一个以编程方式添加的工具栏。当我在 ViewController 中添加工具栏时,一切都很好。但我想像这样创建自己的工具栏类。

class MyOwnToolbar : UIToolbar {


required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    //never called
    self.backgroundColor = UIColor.redColor()
    self.tintColor = UIColor.greenColor()
    self.barTintColor = UIColor.blueColor()
}

override init(frame: CGRect) {
   //error: super.init isn'T called on all paths before returning from initiliazer
}

在我的 ViewController 中,我尝试这样调用:

fromToolBar = MyOwnToolBar() //call nothing?
fromToolBar = MyOwnToolBar(frame: CGRectMake(0,0,0,0)) //doesn't work because init(frame: CGRECT) doesnt work

我的 ViewController 中的旧代码有效:

    self.untilToolBar = UIToolbar(frame: CGRectMake(0,0,0,0))
    untilToolBar?.backgroundColor = redColor
    untilToolBar?.tintColor = greenColor
    untilToolBar?.barTintColor = blueColor

所以我可以使用我的工作解决方案,但我想了解我的代码为什么不起作用。所以也许有人有解决方案或好的链接。

【问题讨论】:

标签: swift init nscoder


【解决方案1】:

这取决于你如何创建 MyOwnToolbar 如果你在界面生成器中添加它并将类连接到 UI 元素使用方法 initWithCoder

如果您以编程方式创建MyOwnToolbar,则应使用initinitWithFrame

例子:

class MyOwnToolbar: UIToolbar {

      private func initialize() {
          self.backgroundColor = UIColor.redColor()
          self.tintColor = UIColor.greenColor()
          self.barTintColor = UIColor.blueColor()
      }

      override init(frame: CGRect) {
          super.init(frame: frame)
          initialize()
      }

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

【讨论】:

    【解决方案2】:

    Oleg 说得对,如果您使用故事板或 xib 来创建视图控制器,那么将调用 init?(coder aDecoder: NSCoder)

    但是您正在以编程方式构建视图控制器,因此将调用 init(frame: CGRect) 而不是 init?(coder aDecoder: NSCoder)

    你应该覆盖init(frame: CGRect):

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.redColor()
        self.tintColor = UIColor.greenColor()
        self.barTintColor = UIColor.blueColor()
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多