它可以是最愚蠢的回答你的問題,但它爲我工作。我不知道如何使用塞繆爾所說的KEy值路徑。
基本上我發了的NSMutableArray存儲的圖標的狀態,紅色或green..YES或NO ..
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"];
END編輯
感謝名單了很多哥們!儘可能簡單! – dottorfeelgood
歡迎。請投票。它會增加我的聲譽:) – Taseen