如何在UITableViewCell上使用自定义初始化程序?

问题描述 投票:1回答:1

我有一个自定义的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)
}
}

我有一个模型类Reflection,我想初始化单元格。但是,在我的视图控制器中,我需要使用tableView.dequeueReusableCell(withIdentifier: "reflectionCell", for: indexPath)。有没有办法让我使用像我制作的自定义初始化程序?

ios swift uitableview
1个回答
1
投票

如果使用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
    }

}

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
}
© www.soinside.com 2019 - 2024. All rights reserved.