Joe Huang
Joe Huang

Reputation: 6560

How to use UITableViewCell with UITableViewCellStyle with cell reuse correctly?

I want to use UITableViewCellStyle.Subtitle style for the default table cells. I found an answer in an SO answer like this:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell?
    if (cell != nil) {
        cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
    }
}

With the code above, I can successfully use the Subtitle cell style. However, I start to think something might be wrong? Why create a new cell when cell != nil? In this way, you never reuse cells, isn't it? Besides, I can just call

let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")

I am having the same result. Why dequeue reusable cell & then create a new one? What is the right way to achieve cell reuse & at the time, to use UITableViewCellStyle.Subtitle style for the cells?

UPDATE

Please note the first block of code is cell != nil, not cell == nil. If I change cell == nil, the code will not use the Subtitle style. I think the first works because it always create new cells with Subtitle style.

Upvotes: 6

Views: 9930

Answers (2)

Craig Siemens
Craig Siemens

Reputation: 13266

If you're using tableView.registerClass, there is no way to override the style that it will pass to the class when each cell is created. A workaround I've used is to create a UITableViewCell subclass called SubtitleCell that always uses the .subtitle style.

import UIKit

class SubtitleCell: UITableViewCell {
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
         super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
    }
}

Then I register that class with the tableView

tableView.register(SubtitleCell.self, forCellReuseIdentifier: "cell")

Upvotes: 16

Kutu
Kutu

Reputation: 191

You are basically right; you dont need the second part of the code.

this:

let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")

will give you a "new" cell if there is none to reuse or an existing one otherwise.

Upvotes: 1

Related Questions