【发布时间】:2016-01-13 09:02:56
【问题描述】:
这是一个示例项目:http://cl.ly/3N2u2i1S441M
我在UITableViewCell 超类中,因为在启动子类时我调用super.init()。在子类和超类的inits 的底部,我调用了一个方法,调用styleCell 对其应用样式。此方法来自它们都遵守的协议,其中一个隐式遵守,因为它是子类并且覆盖了该方法。
在超类“init”的末尾,调用了该样式方法,但它调用了 子类'styleCell 方法,而不是它自己的方法。
到底为什么会这样?
这是 Swift 的错误吗?除了上面的项目之外,我还附加了一些代码来显示问题:
超类表格单元格:
class SuperTableViewCell: UITableViewCell, Style {
var mysuperview: UIView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
mysuperview = UIView()
doStyle()
}
required init?(coder aDecoder: NSCoder) {
fatalError("Must be created in code.")
}
func doStyle() {
print("super class")
}
}
子类表格单元格:
class SubTableViewCell: SuperTableViewCell {
var mysubview: UIView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
mysubview = UIView()
doStyle()
}
required init?(coder aDecoder: NSCoder) {
fatalError("Must be created in code.")
}
override func doStyle() {
super.doStyle()
mysubview!.backgroundColor = UIColor.greenColor()
}
}
样式类和协议:
class StyleManager: NSObject {
}
protocol Style {
func doStyle()
}
这会导致运行时错误,当子类单元格尝试在doStyle() 中设置其视图时发生崩溃。
【问题讨论】:
-
你能贴出代码吗,MCVE?
-
MCVE 是什么意思?我会尽快尝试获取代码。
标签: swift uitableview cocoa-touch inheritance uiview