Bogdan Bogdanov
Bogdan Bogdanov

Reputation: 992

UITableViewCell set contentView backgroundColor with more than one section

In UITableView's didSelectRow method I'm changing the contentView.backgroundColor of the UITableViewCell , but I have 2 sections and when I cast the cell with:

let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)! and set selectedCell.contentView.backgroundColor the code changes the backgroundColor of the both sections. How to cast the cell only from the indexPath.section ?

UPDATE FROM @rmaddy 's answer

When I save in variables indexPath.row and indexPath.section in didSelectRow method and use the variables in willDisplay cell or cellForRow to set the backgroundColor it sets automatically backgroundColor on every 8-16-32-64 row.

UPDATE 2: in cellForRow I'm setting this:

    if(indexPath.row == selectedFromIndex && indexPath.section == selectedFromSection){
        cell.contentView.backgroundColor = UIColor(red: 0, green: 0, blue: 200, alpha: 0.1)
    }else{
        cell.backgroundColor = .clear
        cell.isSelected = false
    }

selectedFromIndex and selectedFromSection are the variables saved in didSelectRowMethod. The selection still appears on rows 8-16-32-64...

Upvotes: 0

Views: 96

Answers (1)

rmaddy
rmaddy

Reputation: 318814

This has nothing to do with casting. You just need an if statement to check the section.

if indexPath.section == 0 { // 1 depending on which section you need
    // get the cell and set the background color
}

But this is going to fail as the user scrolls. What you should be doing in didSelectRow is updating your data model to track which rows have been selected and which rows should get a different color background and then telling the table view to reload that row.

Then your code in cellForRowAt (or willDisplay:forRowAt:) should use that data to set the cell's colors as needed.

In whichever method you do this in, be sure you either set or reset the background color as needed since rows are reused:

// pseudo code:
if row is selected {
    cell.backgroundColor = .someSelectedColor
} else {
    cell.backgroundColor = .someUnselectedColor
}

Upvotes: 2

Related Questions