mugunthan
mugunthan

Reputation: 77

how to set different color for tableview cell

how can I set different color for multiple rows in tableview, maybe up to 10 different colors. I figured the part for alternative row colors.

//alternate row colour
if (indexPath.row % 2) {
    cell.contentView.backgroundColor = [[UIColor alloc]initWithRed:87.0/255.0 green:84.0/255.0 blue:229.0/255.0 alpha:1];
} else {
    cell.contentView.backgroundColor = [[UIColor alloc]initWithRed:187.0/255.0 green:184.0/255.0 blue:229.0/255.0 alpha:1];
}

Upvotes: 0

Views: 1712

Answers (2)

Kirit Modi
Kirit Modi

Reputation: 23407

Generate Random Number CellForRowAtIndex . So each time generate different number.It generate 0 To 15 number so you can set fifteen different background of cell.

NSInteger randomNumber = arc4random() % 16;

After set RGB value in your CellForRewAtIndex.

 cell.contentView.backgroundColor = [[UIColor alloc]initWithRed:randomNumber * 2.0/255.0 green:randomNumber * 3.0/255.0 blue:randomNumber * 4.0/255.0 alpha:1];

Upvotes: 1

cwRichardKim
cwRichardKim

Reputation: 1060

int frequency = indexPath.row %10;
    switch (frequency) {
        case 0:
            //color 1
            break;
        case 1:
            //color 2
            break;
        case 2:
            //color 3
            break;
        case 3:
            //color 4
            break;
            //up to case 9
        default:
            break;
    }

Alternatively, you could set an array of color objects somewhere and then call colors[frequency]. same number of code lines, but not as messy

Upvotes: 1

Related Questions