[self.collectionView reloadData]; UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath]; [self performSegueWithIdentifier:openInFileIdentifier sender:cell];
debug 发现获取的 cell 是 nil,在断点处查看 collection view 的 visibleCells 也是空的。我猜测 reloadData 背后开启了分线程来处理这个事情,所以 reloadData 方法返回的时候,视图并没有完成刷新。
解决方案
去 stackOverFlow 上搜索一下,找到了一个解决方案:UICollectionView 有一个方法,- (void)performBatchUpdates:(void (^)(void))updates completion:(void (^)(BOOL finished))completion; // allows multiple insert/delete/reload/move calls to be animated simultaneously. Nestable.
[self.collectionView reloadData]; [self.collectionView performBatchUpdates:^{ [self.collectionView reloadItemsAtIndexPaths:@[indexPath]]; } completion:^(BOOL finished) { UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath]; [self performSegueWithIdentifier:openInFileIdentifier sender: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; }