我尝试了非常简单的事情:在按下按钮的UICollectionViewCell's
imageView上添加图像。 (实际上,CollectionViewCell
- 是UIImageView
IBOutlet
)
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
self.cell=cell;
return cell;
}
- (IBAction)actionAddImage:(UIBarButtonItem *)sender {
UIImage* image=[UIImage imageNamed:@"1.jpg"];
self.cell.imageView.image=image;
NSIndexPath* path= [self.collectionView indexPathForCell:self.cell];
[self.collectionView reloadItemsAtIndexPaths:@[path]];
}
只有一个细胞。在第一个按钮按下没有任何反应,在第二个 - 图像出现。我把NSLog
,并透露,
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
返回新单元格而不是现有单元格。虽然indexPath
强烈(section = 0,row = 0),即。只有一个细胞。
但是,reloadData
完美无缺,但当然没有动画。
- (IBAction)actionAddImage:(UIBarButtonItem *)sender {
UIImage* image=[UIImage imageNamed:@"1.jpg"];
self.cell.imageView.image=image;
[self.collectionView reloadData];
}
答案 0 :(得分:1)
_array =[NSMutableArray arrayWithObjects:@{@"option":[NSNumber numberWithBool:NO]},@{@"option":[NSNumber numberWithBool:NO]},@{@"option":[NSNumber numberWithBool:NO]},@{@"option":[NSNumber numberWithBool:NO]}, nil];
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
questionImageCollectionViewCell * cell=[self.questionCollectionView dequeueReusableCellWithReuseIdentifier:@"coustomCell" forIndexPath:indexPath];
cell.optionImageView.image=[UIImage imageNamed:[_optionImageArr objectAtIndex:indexPath.item]];
NSDictionary *dic = self.array[indexPath.row];
if ([dic[@"option"] boolValue]) {
[cell.rightTickImg setHidden:NO];
}else{
[cell.rightTickImg setHidden:YES];
}
// [cell.rightTickImg setHidden:YES];
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//[self.array removeObjectAtIndex:indexPath.row];
NSDictionary *dic = @{@"option":[NSNumber numberWithBool:YES]};
[self.array insertObject:dic atIndex:indexPath.row];
[collectionView reloadItemsAtIndexPaths:@[indexPath]];
}
答案 1 :(得分:0)
第一次,您的代码非常不安全。在“collectionView:cellForItemAtIndexPath:”中“创建”时,不应该分配可重用的单元格,而不是尝试这样做:
- (IBAction)actionAddImage:(UIBarButtonItem *)sender
{
NSIndexPath *path = [NSIndexPath indexPathForItem:0 inSection:0]; // i suppose you can reload cell at section 0 position 0
CollectionViewCell *cell = (CollectionViewCell *)[_collectionView cellForItemAtIndexPath:path];
UIImage *image = [UIImage imageNamed:@"1.jpg"];
cell.imageView.image = image;
.... reload _collectionView at Path 'path' ....
}
在其他事情之间,您对可重用单元格所做的外部引用并非在时间上不可变。