How to Set UITableViewCellStyleSubtitle and dequeueReusableCell in Swift?

前端 未结 13 936
攒了一身酷
攒了一身酷 2020-12-01 05:03

I\'d like a UITableView with subtitle-style cells that use dequeueReusableCellWithIdentifier.

My original Objective-C code was

相关标签:
13条回答
  • 2020-12-01 05:47

    Since tableView.dequeueReusableCell(withIdentifier:, for:) return a non-nil cell, the if cell == nil check is always be false. But I found a solution, to makes default style cell become what style(value1, value2 or subtitle) you want, because default style cell's detailTextLabel is nil, so check the detailTextLabel if it's nil, then create new style cell, and give it to dequeue cell, like:

    Swift 3:

    var cell = tableView.dequeueReusableCell(withIdentifier: yourCellReuseIdentifier, for: indexPath)
    
    if cell.detailTextLabel == nil {
        cell = UITableViewCell(style: .value1, reuseIdentifier: repeatCellReuseIdentifier)
    }
    
    cell.textLabel?.text = "Title"
    cell.detailTextLabel?.text = "Detail"
    
    return cell
    

    That's works for me.

    Hope it's help.

    0 讨论(0)
提交回复
热议问题