How to use UITableViewCell with UITableViewCellStyle with cell reuse correctly?

I want to use the UITableViewCellStyle.Subtitledefault style for table cells. I found the answer in 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 above code, I can successfully use the Subtitle cell style. However, I'm starting to think that something might be wrong? Why create a new cell when cell != nil? That way you'll never reuse cells, will you? Alternatively, I can just call

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

I have the same result. Why can you reuse a cell again and then create a new one? What is the correct way to reuse cells while using UITableViewCellStyle.Subtitlecell style ?

UPDATE

, cell != nil, cell == nil. cell == nil, Subtitle. , , Subtitle.

+4
2

tableView.registerClass, , . , , - UITableViewCell SubtitleCell, .subtitle.

import UIKit

class SubtitleCell: UITableViewCell {

    override init(style style: UITableViewCellStyle, reuseIdentifier reuseIdentifier: String?) {
        super.init(style: .subtitle reuseIdentifier: reuseIdentifier)
    }
}

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

; .

:

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

"" , .

+1

Source: https://habr.com/ru/post/1629748/


All Articles