Reputation: 415
So I have a table view with about 150ish rows in the cellForRowAt
method I have the following code
cell.monthLabel.text = String(indexPath.row)
if indexPath.row == 0{
cell.backgroundColor = .blue
}
The question is why at index path 9, 18, 27 and so on have the background color of blue.
Upvotes: 1
Views: 53
Reputation: 984
UITableView doesn't set the data on each item once, it keeps setting the data again and again on all visible items according to the activity going on. i can't give you the clear reason for this behavior but I can give you the solution. Whenever you are setting some data on items with some conditions, always use "Else" statement as well. So for this particular issue you just have to do is to add "Else" block with your "If" condition and set the white background of item in "Else" block.
Upvotes: 0
Reputation: 285059
Cell are reused, you have to set all UI elements to a defined state.
So if you set the backgroundColor
to blue in row 0
if indexPath.row == 0 {
cell.backgroundColor = .blue
}
you have to (re)set it to a default color in all other cases
else {
cell.backgroundColor = .white
}
Upvotes: 2
Reputation: 946
As you do not show all the code of the tableView(_:cellForRowAt:)
method just assume you are dequeuing cells (with the method dequeueReusableCell(withIdentifier:)
and have registered you class for reusing (if you use a custom class).
With this approach the view of the cells gets reused. Meaning that if you do not re-set a property (e.g. background color) it will just use the one form the old cell.
To fix this you can easily include a else in your code and in there set the background color to white.
If you subclass the UITableViewCell
class you can the prepareForReuse()
function to clean up and e.g. reset the background color.
Upvotes: 1