Reputation: 45
I have a collection view in my app. I want to set each item to have a different color. I use a switch case, as follows.
switch indexPath.row {
case 0: cell.label.text = "0"
cell.label.textColor = .blue
case 1: cell.label.text = "1"
case 2: cell.label.text = "2"
case 3: cell.label.text = "3"
case 4: cell.label.text = "4"
case 5: cell.label.text = "5"
default: cell.label.text = "6"
}
I have set the default color light gray to the label. But if I set case 0 to blue color, case 0 and 5 will display blue. I set case 1 to blue color, case 1 and 4 will display blue.
Upvotes: 0
Views: 84
Reputation: 7669
If you want to default color first then before starting switch case set the label default color. In switch
case you can update color based on condition.
Like this:
cell.label.textColor = .ligthGray
switch indexPath.row {
case 0: cell.label.text = "0"
cell.label.textColor = .blue
case 1: cell.label.text = "1"
case 2: cell.label.text = "2"
case 3: cell.label.text = "3"
case 4: cell.label.text = "4"
case 5: cell.label.text = "5"
default: cell.label.text = "6"
}
In this case only the 0
indexed label will be blue
color and the others will be lightGray
Upvotes: 0
Reputation: 9201
It happens because UICollectionView
has a mechanism to reuse the cell's instance. So that's why you should handle cell.label.textColor
in every single case. If not it will be uncontrollable whenever cellForItemAt indexPath
delegate is called. Please try:
switch indexPath.row {
case 0:
cell.label.text = "0"
cell.label.textColor = .blue
case 1:
cell.label.text = "1"
cell.label.textColor = .red
case 2:
cell.label.text = "2"
cell.label.textColor = .orange
case 3:
cell.label.text = "3"
cell.label.textColor = .purple
case 4:
cell.label.text = "4"
cell.label.textColor = .blue
case 5:
cell.label.text = "5"
cell.label.textColor = .blue
default:
cell.label.text = "6"
cell.label.textColor = .blue
}
Upvotes: 1