【发布时间】: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:)' 不能覆盖多个超类声明
如何解决?
【问题讨论】:
-
这是不可能的。这是一个必需的初始化程序。当您覆盖不同的初始化程序时,您必须在任何地方编写它。