ios - `tableView.dequeueReusableCell(withIdentifier:for:)` 从父类调用初始化器

标签 ios swift uitableview

我有一个 tableView ,其中包含使用继承的单元格。有一个共同的祖先,然后有几种具体的实现。公共(public)类不会重写 init(style:reuseIdentifier:) ,而是定义自己的自定义初始值设定项。然而,所有子类都定义了这个初始值设定项,它们在其中从父类(super class)中调用自定义的初始值设定项。现在,在 tableView 中,我注册了子类以供重用,并且将子类出队以供重用。然而,当我尝试将任何子类出队时,出现以下错误:

fatal error: use of unimplemented initializer 'init(style:reuseIdentifier:)' for class 'milan.BotChatBaseCell'

其中 milan.BotChatBaseCell 是父类(super class)。现在,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 上运行。

最佳答案

The common class does not override init(style:reuseIdentifier:) and it rather defines its own custom initializer.

这就是问题所在。通过创建一个新的指定初始化器,您已经放弃了继承,因此 BotChatBaseCell 不再继承指定初始化器 init(style:reuseIdentifier:)。它必须实现这一点。

一个可能的解决方案是让你的新初始化器成为一个便利的初始化器,从而允许继承继续工作。另一种可能的解决方案是添加 init(style:reuseIdentifier:) 的覆盖,即使它是微不足道的(即它只是调用 super)。

关于ios - `tableView.dequeueReusableCell(withIdentifier:for:)` 从父类调用初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46156762/

相关文章:

javascript - xcode 中的 HTML5 和 javascript

swift - 在 View 加载时选择一行

iphone - 我用MailCode写邮件客户端有点麻烦

iphone - 在 Objective-C 中访问实例属性的最佳实践?

iphone - EXC_BAD_ACCESS - 我怎样才能避免它?

swift - 将方向应用于 CGContext

ios - XLPagerTabStrip 选择首先显示的 View Controller

ios - 选择时向表格单元格添加滑动 View

ios - 将目标添加到 UITableview 中的 UITextField (Swift)

ios - UISearchController 保留问题