Ahmet Sina Ustem
Ahmet Sina Ustem

Reputation: 1090

How can I set UITableViewCell backgroundColor in section without repeating?

I have a UITableView and i have already set its cell backgroundColor like this.

cell.backgroundColor = indexPath.row % 2 == 0 ?
            UIColor.Cell.oddBackgroundColor : UIColor.Cell.evenBackgroundColor

But when i set up tableView with sections, cells in section set their background color as above again.

For example :

As you can see the last cell in section 0 and the first cell in section 1 are same background color. It must be different and section 1 must different order for its cell background colors.

For example:

Cell background colors with section:

How can i do like above example?

Upvotes: 1

Views: 82

Answers (1)

RajeshKumar R
RajeshKumar R

Reputation: 15758

//var row = indexPath.row
//for i in 0..<indexPath.section {
//    row += tableView.numberOfRows(inSection: i)
//}
let row = (0..<indexPath.section).reduce(indexPath.row) { $0 + tableView.numberOfRows(inSection: $1) }
cell.backgroundColor = row % 2 == 0 ? UIColor.gray : UIColor.white

enter image description here

Upvotes: 1

Related Questions