0

I'm trying to add a color of a specific gradient to each cell of a table view. So far all I've managed to do, is set the gradient for each of the cells. I've found another post which is close to mine but only sets two colors for alternating rows by determining the number of rows and attributing a certain color depending on whether the row number is pair or not. Here's the link. Here is the code I am using for the gradient of each cell; how do i attribute each color of the gradient to a cell instead?

    CAGradientLayer *grad = [CAGradientLayer layer];
    grad.frame = cell.bounds;

    grad.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:252/255.f green:135/255.f blue:208/255.f alpha:1] CGColor], (id)[[UIColor colorWithRed:253/255.f green:91/255.f  blue:105/255.f alpha:1] CGColor], nil];

    [cell setBackgroundView:[[UIView alloc] init]];
    [cell.backgroundView.layer insertSublayer:grad atIndex:0];

Thanks!

Community
  • 1
  • 1
  • Do you have solution for http://stackoverflow.com/questions/30478975/how-to-set-multiple-gradient-colour-in-uitableviewcell-using-cagradientlayer-in – Nischal Hada May 28 '15 at 05:55

1 Answers1

0

In your cellForRowAtIndexPath, You can add a switch statement with as many cases as you need to fit the number of cells you have. Here is the code:

switch (indexPath.row) {
    case 0:
        cell.backgroundColor = [[UIColor colorWithRed:252/255.f green:135/255.f blue:208/255.f alpha:1] CGColor]
        break;
    case 1:
        cell.backgroundColor = [[UIColor colorWithRed:253/255.f green:91/255.f  blue:105/255.f alpha:1] CGColor]
        break;
    default:
        cell.backgroundColor = //aother GCColor of your choice
        break;
}

and so on. For your first cell, you will use case 0, for the second cell use case 1, and so on. You can add as many cases as you need to match the number of cells you have. And make sure you use default: for the last cell.

Steve Sahayadarlin
  • 1,164
  • 3
  • 15
  • 32