美文网首页程序员iOS技术点
如何获取UICollectionView的某个Cell

如何获取UICollectionView的某个Cell

作者: 码渣 | 来源:发表于2018-05-15 17:38 被阅读31次

可能你会遇这种情况:collectionView每个cell是屏幕大小,然后上面添加了tableview,tableview可以上拉加载更多,当上拉加载完数据后,我们可以2种方式更新UI,如下

//第一种:简单粗暴
[self.collectionView reloadData];
//第二种: 获取cell,然后传值更新UI
GBPracticeRecordCollectionViewCell *cell = (GBPracticeRecordCollectionViewCell*)[self.collectionView 
cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];

但有时候在加载过程中,你会左右滑动collectionview 使得当前加载数据的cell不在屏幕内,此时通过上面方法2是无法获取cell,通过debug可知为nil,那么有什么办法呢

继续往下看
我们可以先让collectionView滚动到目标cell处,然后当滚动结束时,在scrollView的代理方法中,来获取cell,传值更新UI

//滚到目标cell上
[self.collectionView selectItemAtIndexPath:
[NSIndexPath indexPathForItem:index inSection:0] 
animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
_needOpenCellIndexPath = [NSIndexPath indexPathForItem:index inSection:0];
//获取目标cell
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    if (_needOpenCellIndexPath) {
        GBPracticeRecordCollectionViewCell *cell = (GBPracticeRecordCollectionViewCell*)[self.collectionView cellForItemAtIndexPath:_needOpenCellIndexPath];
        //传值
        cell.practiceRecord = _practiceRecords[_needOpenCellIndexPath.item];
        //结束刷新
        [cell endRefreshing];
        _needOpenCellIndexPath = nil;
    }
}

相关文章

网友评论

    本文标题:如何获取UICollectionView的某个Cell

    本文链接:https://www.haomeiwen.com/subject/wmrydftx.html