对于您的问题,这可能是最愚蠢的答案,但它对我有用。我不知道如何使用 Samuel 所说的 KEY 值路径。
基本上我做了一个 NSMutableArray 来存储图标的状态,红色或绿色..是或否..
selState = [[NSMutableArray alloc] initWithObjects:@"NO",@"NO",@"NO",@"NO",nil ];
然后在“ItemForIndexPath”方法中,检查为该项目设置图像的值
if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"]) {
image = [UIImage imageNamed:@"ICUbedGREEN.png"];
}
else
{
image = [UIImage imageNamed:@"ICUbedRED.jpg"];
}
选择项目时,使用 IndexPath 将 NO 的值更改为 YES,反之亦然。
if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"]) {
[selState replaceObjectAtIndex:indexPath.row withObject:@"YES"];
}
else if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"YES"]) {
[selState replaceObjectAtIndex:indexPath.row withObject:@"NO"];
}
然后更新了集合视图
[self.collectionView reloadData];
所有代码都在这里
@interface ViewController (){
NSMutableArray *selState;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
selState = [[NSMutableArray alloc] initWithObjects:@"NO",@"NO",@"NO",@"NO",nil ];
}
-(NSInteger)numberOfSectionsInCollectionView:
(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section
{
return 4;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
Cell *myCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
UIImage *image;
if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"]) {
image = [UIImage imageNamed:@"ICUbedGREEN.png"];
}
else
{
image = [UIImage imageNamed:@"ICUbedRED.jpg"];
}
myCell.imageView.image = image;
return myCell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath: (NSIndexPath *)indexPath
{
if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"]) {
[selState replaceObjectAtIndex:indexPath.row withObject:@"YES"];
}
else if ([[selState objectAtIndex:indexPath.row] isEqualToString:@"YES"]) {
[selState replaceObjectAtIndex:indexPath.row withObject:@"NO"];
}
[self.collectionView reloadData];
}
@end
谢谢
编辑---->>
上面ItemForIndexPath中的代码也可以写成
image = [[selState objectAtIndex:indexPath.row] isEqualToString:@"NO"] ?
[UIImage imageNamed:@"ICUbedGREEN.png"] : [UIImage imageNamed:@"ICUbedRED.jpg"];
结束编辑