Search code examples
swiftuicollectionviewcellcollectionview

Swift CollectionView Display Wrong


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.


Solution

  • 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
    }