【发布时间】:2017-09-11 13:21:08
【问题描述】:
我有一个tableView,其中包含使用继承的单元格。有一个共同的祖先,然后有几个具体的实现。公共类不会覆盖init(style:reuseIdentifier:),而是定义了自己的自定义初始化程序。然而,所有的子类都定义了这个初始化器,它们从超类中调用自定义的初始化器。现在在tableView 中,我注册了子类以供重用,并且我正在使子类出列以供重用。然而,当我尝试使任何子类出队时出现以下错误:
fatal error: use of unimplemented initializer 'init(style:reuseIdentifier:)' for class 'milan.BotChatBaseCell'
其中milan.BotChatBaseCell 是超类。现在milan.BotChatBaseCell 从未注册到tableView。知道为什么会这样吗?
代码:
import UIKit
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(ExampleBotChatCell.self, forCellReuseIdentifier: "ExampleBotChatCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleBotChatCell", for: indexPath) as! ExampleBotChatCell
return cell
}
}
class BotChatBaseCell: UITableViewCell {
init(style: UITableViewCellStyle, reuseIdentifier: String?, customString: String) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
print(">>>> nice \(customString)")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ExampleBotChatCell: BotChatBaseCell {
init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier, customString: "Example")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
我刚刚测试过,它适用于 Swift 3.2,但不适用于 Swift 4。
【问题讨论】:
-
看过这个answer
-
然而你在超类中定义
init(style:reuseIdentifier:)仍然需要在每个子类中实现,即使你没有使用它并且不要忘记调用 super.init(style:) -
请不要只谈论您的代码。 显示它。给我们一些我们可以复制并粘贴到项目中并查看问题的东西。最起码,展示公共类的相关部分!
-
@milan-nosáľ : 展示您的 cellForRowAtIndexPath 实现,然后我们将能够为您提供帮助
-
编辑了问题
标签: ios swift uitableview