如何在UICollectionView reloadData后找到的某个cell
2015-12-08 22:12
489 查看
collection view 在reloadData之后,找不到 cell
今天碰到的一个问题:app 主界面是一个 collection view,当数据源增加一个数据时,我需要立即刷新视图,并打开相应的 cell。于是我写了如下代码,
1 2 3 | [self.collectionView reloadData]; UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath]; [self performSegueWithIdentifier:openInFileIdentifier sender:cell]; |
解决方案
去 stackOverFlow 上搜索一下,找到了一个解决方案:UICollectionView 有一个方法,
1 | - (void)performBatchUpdates:(void (^)(void))updates completion:(void (^)(BOOL finished))completion; // allows multiple insert/delete/reload/move calls to be animated simultaneously. Nestable. |
1 2 34 | [self.collectionView reloadData]; [self.collectionView performBatchUpdates:^{ [self.collectionView reloadItemsAtIndexPaths:@[indexPath]]; } completion:^(BOOL finished) { UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath]; [self performSegueWithIdentifier:openInFileIdentifier sender:cell]; }]; |
如果 cell 不在视图内呢?
如果 cell 刚好不在屏幕区域内,处于 visible 的状态,那么用上述方法依然会找不到 cell。我想可以先让 collection view 滚动到目标 cell 处,然后在打开 cell。这里需要用到 scroll 的代理方法,以在滚动动画结束的时候,找到目标 cell。(滚动结束才能确定目标 cell 是 visible 的。)你还需要定义一个 indexPath 值以区分滚动结束的时候是否需要打开cell,以及要打开哪个 cell。代码如下,
1 2 34 | 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 - |
相关文章推荐
- 解决iOS UITextView没有placeholder
- 【Codeforces Round 276 (Div 2)D】【数论 正难则反 枚举倍数 二分 O(nlogn)】Maximum Value n个数大数mod小数找最大余数
- UIView的bounds到底是干嘛的
- Query.extend() 函数详解-转载
- 旧Mj下拉刷新 An instance 0xca90200 of class UITableView was deallocated while key value observers were s
- UVALive-2531 The K-League (最大流建模+枚举)
- lucene的多种搜索2-SpanQuery
- UITableViewCell contentView layoutSubviews 死循环
- js实现卡片式项目管理界面UI设计效果
- lucene-SpanQuery跨度查询基础
- Lucene中的 Query对象
- lucene-SpanFirstQuery 和SpanNearQuery 跨度查询
- lucene-SpanNotQuery和SpanOrQuery交迭与全局跨度
- ios学习笔记(七)关于NSUInteger
- ios学习笔记(七)关于NSUInteger
- Palindrome subsequence(区间dp)
- JavaEE_Request和Response的区别
- UI的第一天
- UIView初始化:initWithFrame与initWithCoder的区别
- DoTween - Sequence