Alex Vihlayev Alex Vihlayev - 3 months ago 11
iOS Question

UITableViewCell's background settings are reseted on scroll

I need help! I searched a lot, but really don't know what to do.

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:




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

else {
    cell.backgroundColor = UIColor.white