Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 716
Joe Huang Avatar asked Feb 21 '16 06:02

Joe Huang


1 Answers

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")
like image 168
Craig Siemens Avatar answered Nov 09 '22 21:11

Craig Siemens