gpt4 book ai didi

ios - Swift 初始化方法错误 : Declaration 'init(coder:)' cannot override more than one superclass declaration

转载 作者:行者123 更新时间:2023-11-29 05:30:21 28 4
gpt4 key购买 nike

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

我只想重写 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' initializer 'init(coder:)' must be provided by subclass of '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提示其次,

Declaration 'init(coder:)' cannot override more than one superclass declaration

<小时/>

如何解决?

最佳答案

您可以从 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)
}
}

我们使用便利重写 init 来传达这是一个便利 init,它与父类(super class)中指定的初始化程序具有相同的签名。

关于ios - Swift 初始化方法错误 : Declaration 'init(coder:)' cannot override more than one superclass declaration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57655943/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com