Change image in collectionView to match purchased items held in an Array

49 views Asked by At

I have an array of NSNumbers which I would like to use to change the image of a UICollectionView cell if each of those numbers is equal to the indexPath row of the collectionView.

I'm aware that I can use:

if [indexPath row] == 5 {

self.myImage = [UIImage imageNamed:@"120-red.png"];
            aCell.imageView.image = self.myImage;
}

for a single value, but how do I do this from an array?

btw. its a dynamic NSMutableArray which is created from purchased products and stored in NSUserDefaults. Any help is much appreciated!

1

There are 1 answers

0
Nurep On BEST ANSWER

You could save your indexes and image names in a dictionary with the keys being NSNumbers.

NSDictionary* dict = @{@(5):@"120-red.png", @(6):@"130-blue.png"};

Then in your dataSource method

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
              cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString* str = [dict objectForKey:@(indexPath.row)];
    if (str) { //str will be nil if the key isn't in the dictionary
        image = [UIImage imageNamed: str];
    }
    else {
        //the key wasn't in your dictionary. Do whatever you did before to keep this cell the same
    }
}

When you change the data you need to reload it. Either use:

- (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths

To reload only the ones you changed,

OR

- (void)reloadData

To reload the whole collection