user3344977
user3344977

Reputation: 3604

Need to assign each UICollectionViewCell a background color and colors must stay in a specific order even while scrolling

I have a set of 13 colors. I need to assign these colors to the backgroundColor property of UICollectionViewCells as the user scrolls through a UICollectionView.

So far this works perfectly, but I need to take it one step further. I need to have the colors appear in a specific order at all times.

Here's a quick example. Pretend I only have 3 colors: red, yellow, and green. When the collection view first loads the user would see a red cell, yellow cell, and green cell. If the user scrolls all the way down, and then starts to scroll back up they would see a green cell, a yellow cell, and then a red cell.

Notice how the order of colors stayed the same the entire time? My problem is finding a way to do this with my 13 colors.

Normally I would just set an array of colors and access the index of that array using indexPath.row in cellForItemAtIndexPath like you would any other normal data array for a table view or collection view, but once I have more than 13 objects in my data array, the row count becomes bigger than my color array count and an exception will be thrown.

I also tried keeping track of the colors using an int property, but this just doesn't work. The colors are always off, even if just by one color.

I also realize that I could just create 13 separate UICollectionViewCell subclasses, hard code the backgroundColor, give them all different identifiers, and try and setup some switching logic in cellForItemAtIndexPath but this seems like a lot of work just for a background color and it would also be more memory intensive on the system and I want to avoid lag as much as possible.

Upvotes: 0

Views: 86

Answers (1)

tbaranes
tbaranes

Reputation: 3590

You should continue on your first idea: an array of your 13 colors. Once you have that, you can use the % operator on the number of elements you have in your array to be sure to have always a correct index, and the right one to keep the order wanted:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    /* Do what you have to do... */

    UIColor *color = [myArrayOfColor objectAtIndex:indexPath.row % [myArrayOfColor count]];
    [cell setBackgroundColor:color];    
    return cell;    
}

Upvotes: 1

Related Questions