Alex Vihlayev
Alex Vihlayev

Reputation: 23

UITableViewCell's background settings are reset on scroll

I have a UITableView Controller in my project. So I made a UITableViewCell setup like here:

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

    cell.textLabel?.text = "Section: \(indexPath.section). Row: \(indexPath.row)."

    if indexPath.row % 2 == 1 {
        cell.backgroundColor = UIColor.gray
    }

    return cell
}

I want my tableview's cells to be gray if their index is not divisible by 2.

When tableview appears, everything is perfect! But when I scroll up and down, cells starts to change their colors to gray.

So at the end all my cells are gray.

Here are some images:

before

after

Upvotes: 2

Views: 279

Answers (3)

alexburtnik
alexburtnik

Reputation: 7741

The problem is that you never set background back to white. Since cells are being reused, at some point you set gray for all of them. Instead you should check the row index every time cell is reused:

cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.white : UIColor.gray

Upvotes: 2

radkrish
radkrish

Reputation: 177

Because tableview reuses the cell

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

cell.textLabel?.text = "Section: \(indexPath.section). Row: \(indexPath.row)."

if indexPath.row % 2 == 1 {
    cell.backgroundColor = UIColor.gray
}else{
    cell.backgroundColor = YOUR_COLOR
}
return cell

}

Edit : Gellert Lee answered it first and quite simple

Upvotes: 0

Dovahkiin
Dovahkiin

Reputation: 1239

Try to add an else statement, since the cells are reused.

else {
    cell.backgroundColor = UIColor.white
}

Upvotes: 4

Related Questions