[英]collectionView: reloadData works, reloadItemsAtIndexPaths does not
[英]UICollectionView reloadData works, but reloadItemsAtindexPaths not
我尝试了很简单的事情:在按下按钮的UICollectionViewCell's
添加图像。 (实际上, 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];
}
_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]];
}
第一次,您的代码非常不安全。 在“ 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' ....
}
在其他方面,您对可重复使用的单元格所做的外部引用在时间上并非一成不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.