How can i dynamically change colors of the table prototype cell labels in the interval

i have been searching a logic to dynamically change colors of labels in the tableView , i am using an arrayList to print subjects (hindi,english,maths,punjabi, geography) printed on the tabels prototype cell , now i want to change colors of all the subjects in the interval of every three , like first cell label should be red, second should be green , and third should be white , and follow this dynamic rule for furthur cells

here is the method i used to print static cell label colors

    switch subjectsList[indexPath.row] {
    case subjectsList[1],subjectsList[4]:
        cell.subjectFirstLetter.textColor = UIColor.orange
    case subjectsList[2],subjectsList[5]:
        cell.subjectFirstLetter.textColor = UIColor.red
    default:
        cell.subjectFirstLetter.textColor = UIColor.white
    }

how can i make this dynamic ?

Update :- solved

let remainder = indexPath.row % 3
switch remainder {
case 1:
    cell.subjectFirstLetter.textColor = .orange
case 2:
    cell.subjectFirstLetter.textColor = .red
default: // e.g. zero
    cell.subjectFirstLetter.textColor = .white
}

2 answers

  • answered 2018-09-17 06:03 zisoft

    Use Modulo:

    let color: UIColor
    
    switch indexPath.row % 3 {
    case 0:
        color = UIColor.red
    case 1:
        color = UIColor.green
    case 2:
        color = UIColor.white
    default:
        break
    }
    
    cell.subjectFirstLetter.textColor = color
    

  • answered 2018-09-17 06:04 JonJ

    Use the modulo (remainder) operator here with the indexPath to set the label color:

    let remainder = indexPath.row % 3
    switch remainder {
    case 1:
        cell.subjectFirstLetter.textColor = .orange
    case 2:
        cell.subjectFirstLetter.textColor = .red
    default: // e.g. zero
        cell.subjectFirstLetter.textColor = .white
    }
    

    (Note that you can use the shortcut for accessing UIColor here.)