更改 collectionView 中的图像以匹配数组中保存的购买项目
Change image in collectionView to match purchased items held in an Array
我有一个 NSNumber 数组,我想用它来更改 UICollectionView
cell 的图像,如果每个数字都等于 [= collectionView
行.
我知道我可以使用:
if [indexPath row] == 5 {
self.myImage = [UIImage imageNamed:@"120-red.png"];
aCell.imageView.image = self.myImage;
}
对于单个值,但我如何从数组中执行此操作?
顺便说一句。它是根据购买的产品创建并存储在 NSUserDefaults
中的动态 NSMutableArray
。非常感谢任何帮助!
您可以将索引和图像名称保存在字典中,键为 NSNumbers。
NSDictionary* dict = @{@(5):@"120-red.png", @(6):@"130-blue.png"};
然后在你的数据源方法中
-(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
}
}
当您更改数据时,您需要重新加载它。要么使用:
- (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths
要仅重新加载您更改的那些,
或
- (void)reloadData
重新加载整个集合
我有一个 NSNumber 数组,我想用它来更改 UICollectionView
cell 的图像,如果每个数字都等于 [= collectionView
行.
我知道我可以使用:
if [indexPath row] == 5 {
self.myImage = [UIImage imageNamed:@"120-red.png"];
aCell.imageView.image = self.myImage;
}
对于单个值,但我如何从数组中执行此操作?
顺便说一句。它是根据购买的产品创建并存储在 NSUserDefaults
中的动态 NSMutableArray
。非常感谢任何帮助!
您可以将索引和图像名称保存在字典中,键为 NSNumbers。
NSDictionary* dict = @{@(5):@"120-red.png", @(6):@"130-blue.png"};
然后在你的数据源方法中
-(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
}
}
当您更改数据时,您需要重新加载它。要么使用:
- (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths
要仅重新加载您更改的那些,
或
- (void)reloadData
重新加载整个集合