如何在 UITableViewCell 上使用自定义初始值设定项?

A T*_*hka 6 uitableview ios swift

我有一个自定义 UITableViewCell,我想在我的表格视图中使用它。这是我的单元格代码:

class ReflectionCell: UITableViewCell {

@IBOutlet weak var header: UILabel!
@IBOutlet weak var content: UILabel!
@IBOutlet weak var author: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
}

init(data: Reflection) {
    self.header.text = data.title
    self.content.text = data.content
    self.author.text = data.author.name
    super.init(style: UITableViewCellStyle.default, reuseIdentifier: "reflectionCell")
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}
}
Run Code Online (Sandbox Code Playgroud)

我有一个模型类Reflection,我想用它来初始化单元格。但是,在我的视图控制器中,我需要使用tableView.dequeueReusableCell(withIdentifier: "reflectionCell", for: indexPath). 有什么方法可以让我使用像我制作的那样的自定义初始值设定项吗?

Rob*_*Rob 7

如果使用dequeueReusableCell,则无法更改调用的初始化方法。但是您可以编写自己的方法来更新 IBOutlets,然后在您成功使单元出列后调用该方法。

class ReflectionCell: UITableViewCell {

    @IBOutlet weak var header: UILabel!
    @IBOutlet weak var content: UILabel!
    @IBOutlet weak var author: UILabel!

    func update(for reflection: Reflection) {
        header.text = reflection.title
        content.text = reflection.content
        author.text = reflection.author.name
    }

}
Run Code Online (Sandbox Code Playgroud)

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! ReflectionCell
    cell.update(for: reflections[indexPath.row])
    return cell
}
Run Code Online (Sandbox Code Playgroud)

  • 重点是初始化单元格,而不是更新它。该方案必须允许您在实例化时首次添加视图。接受的答案可以用存储变量的 didSet 闭包替换。 (3认同)
  • “dequeueReusableCell”的全部要点是显式_不_为每一行初始化一个新单元格,而是在可能的情况下查看是否有以前使用过的单元格现在可供重用,然后更新它。 (3认同)