Gonzalo Fuentes
Gonzalo Fuentes

Reputation: 23

Xcode UITableView Cell Background not working

I want to color a single TableViewCell, and in the beginning it works correctly, but then it just messes up and colors also other random cells.

I'm leaving the code and some screenshots, hope you can help. I'm using Xcode 9 and swift 4.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Linea", for: indexPath)
    cell.textLabel?.text = ListaLineas[indexPath.row]
    if (cell.textLabel?.text == "TifloInnova"){
        cell.textLabel?.textColor = UIColor(red: 100, green: 100, blue: 100, alpha: 1)
        cell.contentView.backgroundColor = UIColor(red:100.0, green: 0.0, blue:0.0, alpha:0.8)
    }
    else{
        cell.textLabel?.textColor = UIColor(red: 0.0, green: 0.478, blue: 1, alpha: 1.0)
    }
    cell.textLabel?.numberOfLines = 6
    cell.textLabel?.font.withSize(15)
    cell.textLabel?.textAlignment = .center
    cell.textLabel?.lineBreakMode = .byWordWrapping

    tableView.estimatedRowHeight = 80
    tableView.rowHeight = UITableViewAutomaticDimension

    return cell;
}

Many thanks. I want it to looks like this

But sometimes it looks like this

Upvotes: 2

Views: 72

Answers (2)

mugx
mugx

Reputation: 10105

You may reset the background color in the "else" branch, doing so:

if cell.textLabel?.text == "TifloInnova" {
   cell.contentView.backgroundColor = UIColor.red
} else {
   cell.contentView.backgroundColor = UIColor.clear    
}

Upvotes: 1

Ahmad F
Ahmad F

Reputation: 31685

The solution for your case is make sure that if the cell text label is not "TifloInnova" to return the color to the default. You could implementa it as follows:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Linea", for: indexPath)
        cell.textLabel?.text = ListaLineas[indexPath.row]

        if (cell.textLabel?.text == "TifloInnova"){
            cell.textLabel?.textColor = UIColor(red: 100, green: 100, blue: 100, alpha: 1)
            cell.contentView.backgroundColor = UIColor(red:100.0, green: 0.0, blue:0.0, alpha:0.8)
        }else{
            cell.textLabel?.textColor = UIColor(red: 0.0, green: 0.478, blue: 1, alpha: 1.0)
            // here what you should add, for instance the default color should be white:
            cell.contentView.backgroundColor = UIColor.white
        }
        cell.textLabel?.numberOfLines = 6
        cell.textLabel?.font.withSize(15)
        cell.textLabel?.textAlignment = .center
        cell.textLabel?.lineBreakMode = .byWordWrapping

        tableView.estimatedRowHeight = 80
        tableView.rowHeight = UITableViewAutomaticDimension

        // btw no need for the ";" :)
        return cell
}

Upvotes: 1

Related Questions