【问题标题】:Swift init method error: Declaration 'init(coder:)' cannot override more than one superclass declarationSwift init 方法错误:声明 'init(coder:)' 不能覆盖多个超类声明
【发布时间】:2019-08-26 10:16:28
【问题描述】:

我的项目中有很多自定义视图(UIView 的子类)。我需要重写init 方法。

我只想override init(frame: CGRect) 方法。而且我不想在许多 UIView 子类中一次又一次地编写相同的代码init?(coder

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

然后我给 UIView 添加一个扩展,然后就OK了。

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

}

当我自定义 UITableView 类时,问题就出现了。

class Table: UITableView {

    override init(frame: CGRect, style: UITableView.Style) {
        super.init(frame: frame, style: style)
    }

Xcode 提示优先,

'required'初始化器'init(coder:)'必须由'UITableView'的子类提供

class Table: UITableView {

    override init(frame: CGRect, style: UITableView.Style) {
        super.init(frame: frame, style: style)
    }

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

Xcode 提示其次,

声明 'init(coder:)' 不能覆盖多个超类声明


如何解决?

【问题讨论】:

  • 这是不可能的。这是一个必需的初始化程序。当您覆盖不同的初始化程序时,您必须在任何地方编写它。

标签: ios swift uikit


【解决方案1】:

您可以从作为 UITableView 子类的 BaseTableView 类继承您的 CustomTableView 类。 BaseTableView 类将同时包含 UITableView 的初始化方法。例如:

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

    override init(frame: CGRect, style: UITableView.Style) {
        super.init(frame: frame, style: style)
    }
}

然后你的自定义类是从 BaseTableView 类继承的,有一个方便的重写方法 init(frame:...

class Table1: BaseTableView {
    convenience override init(frame: CGRect, style: UITableView.Style) {
        self.init(frame: frame, style: style)
    }
}

class Table2: BaseTableView {
    convenience override init(frame: CGRect, style: UITableView.Style) {
        self.init(frame: frame, style: style)
    }
}

我们使用便利覆盖初始化来传达这是一个便利初始化,它与超类中的指定初始化程序具有相同的签名。

【讨论】:

    【解决方案2】:

    因为convenience initrequired init 发生冲突。初始化器的实现不能超过一个。

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 1970-01-01
      • 2014-07-18
      • 2017-11-20
      • 2013-06-03
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 2016-08-27
      相关资源
      最近更新 更多