Christopher Graf
Christopher Graf

Reputation: 2219

How do you initialize/use UITableViewCells with CellStyle = .value1 programmatically?

I want to use Apple's given Cell Style value1 for my cells and I am not sure how this is done correctly. The only possible way to set the cell style is during the Cell's initialization, but I don't think subclassing should be necessary in this case.

What would be the correct way to set the CellType? I tried to get it done in tableView(_:cellForRowAt:), but dequeueReusableCell(withIdentifier:for:) does not return an Optional, which is why my logic cannot work.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "myCellIdentifier", for: indexPath)

    if cell == nil {
        cell = UITableViewCell.init(style: .value1, reuseIdentifier: "myCellIdentifier")
    }

    // setup cell text and so on
    // ...

    return cell
}

Upvotes: 0

Views: 1745

Answers (1)

DonMag
DonMag

Reputation: 77442

Don't call tableView.register(...)

Instead, use this approach in cellForRowAt:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // try to dequeue a cell
    var cv1 = tableView.dequeueReusableCell(withIdentifier: "cv1")

    // if that fails, create a new one
    if cv1 == nil {
        cv1 = UITableViewCell(style: UITableViewCell.CellStyle.value1, reuseIdentifier: "cv1")
    }

    // just for sanity
    guard let cell = cv1 else { fatalError("Failed to get a cell!") }

    // set the cell properties as desired
    cell.contentView.backgroundColor = .yellow
    cell.detailTextLabel?.text = "Row \(indexPath.row)"
    return cell

}

Upvotes: 2

Related Questions