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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With