A Tyshka
A Tyshka

Reputation: 4090

How can I use a custom initializer on a UITableViewCell?

I have a custom UITableViewCell and I'd like to use it in my table view. Here's my code for the cell:

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)
}
}

I have a model class Reflection that I'd like to initialize the cell with. However, in my view controller I need to use tableView.dequeueReusableCell(withIdentifier: "reflectionCell", for: indexPath). Is there any way for me to use a custom initializer like the one I made?

Upvotes: 10

Views: 11783

Answers (1)

Rob
Rob

Reputation: 437442

If you use dequeueReusableCell you cannot change which initializer method that is called. But you can write your own method to update the IBOutlets which you then call after you successfully dequeue a cell.

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
    }

}

And

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
}

Upvotes: 11

Related Questions