iOS UICollectionView reloadData后找到某个cell 更新某个cell数据

在开发中有个需求, 要在刷新完数据后再修改其中某些cell的属性, 结果发现是有问题的

    [self.collectionView reloadData];
    UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];

debug发现在执行完reloadData方法后并没有立即刷新cell, 而是执行了下面对cell操作的代码, 当这个方法执行完成后reloadData才会去刷新数据, 从而导致我们对cell的操作又被刷新的时候修改了

要解决这个问题 ,可以这么操作

    [self.collectionView reloadData];
    NSMutableArray *indexPaths = [NSMutableArray array];
    for (int i = 0; i < 10 ; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [indexPaths addObject:indexPath];
    }
    [self.collectionView performBatchUpdates:^{
        [self.collectionView reloadItemsAtIndexPaths:indexPaths];
    } completion:^(BOOL finished) {

    for (NSIndexPath *indexPath in indexPaths) {
        UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
        cell.backgroundColor = [UIColor redColor];

        }
    }];

如果操作的cell未在现实区域,可以这么操作(此方法来源于网络)
可以先让 collection view 滚动到目标 cell 处,然后在打开 cell。这里需要用到 scroll 的代理方法,以在滚动动画结束的时候,找到目标 cell。(滚动结束才能确定目标 cell 是 visible 的。)你还需要定义一个 indexPath 值以区分滚动结束的时候是否需要打开cell,以及要打开哪个 cell。代码如下,

NSIndexPath *needOpenCellIndexPath;

- (void)foo
{
    needOpenCellIndexPath = ...;
    [self.collectionView performBatchUpdates:^{
        [self.collectionView reloadItemsAtIndexPaths:@[needOpenCellIndexPath]];
    } completion:^(BOOL finished) {
        UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:needOpenCellIndexPath];
        if (cell) {
            [self performSegueWithIdentifier:RPAOpenMapSegueIdentifier sender:cell];
        } else {
            // Start scrolling to the target cell.
            [self.collectionView selectItemAtIndexPath:needOpenCellIndexPath animated:YES scrollPosition:UICollectionViewScrollPositionTop];
        }    
    }];
}

#pragma mark - scroll view deleagte
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (needOpenCellIndexPath) {
        UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:needOpenCellIndexPath];
        [self performSegueWithIdentifier:openInFileIdentifier sender:cell];
    }
    needOpenCellIndexPath = nil;
}
#pragma mark -
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值