uicollectionview在reloaddata之后立即select一个项目?

调用之后-[UICollectionView reloadData]需要一些时间来显示单元格,所以在调用reloadData之后立即select一个项目不起作用。 有没有办法在reloadData之后立即select一个项目?

沿着这个答案的线我发现,调用layoutIfNeededreloadData似乎有效地“刷新”重新加载之前,我做其他事情的collectionView:

 [self.collectionView reloadData]; [self.collectionView layoutIfNeeded]; ... 

在网页上,我发现这个解决scheme,一些评论者表示,它不适用于iOS 9的他们,但对我来说,这样可以改变你的里程。

我正在处理collectionView: cellForItemAtIndexPath:的单元格的select。 我发现的问题是,如果单元格不存在,只需调用selectItemAtIndexPath: animated: scrollPosition:实际上不会select该项目。

相反,你必须这样做:

cell.selected = YES;
[m_collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];

不要使用reloadData

使用- (void)performBatchUpdates:(void (^)(void))updates completion:(void (^)(BOOL finished))completion代替。 完成单元插入/删除等animation完成后执行完成块。 您可以将调用reloadData放在(void (^)(void))updates块中

苹果说:

您不应该在插入或删除项目的animation块中间调用此方法。 插入和删除操作会自动使表的数据得到适当的更新。

事实上,你不应该在任何animation(包括滚动的UICollectionView中调用这个方法。

所以,你可以使用:

 [self.collectionView setContentOffset:CGPointZero animated:NO]; [self.collectionView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; 

或者确定没有任何animation,然后调用reloadData ; 要么

 [self.collectionView performBatchUpdates:^{ //insert, delete, reload, or move operations } completion:nil]; 

希望这对你有帮助。

迅捷方式:

 let selected = collectionView.indexPathsForSelectedItems() collectionView.performBatchUpdates({ [weak self] in self?.collectionView.reloadSections(NSIndexSet(index: 0)) }) { completed -> Void in selected?.forEach { [weak self] indexPath in self?.collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: []) } } 

确保你在主线程上调用了reloadData 。 这可能是您的单元更新延迟的原因。

我在willDisplayCell colelctionView委托上处理它。 想法:需要一个临时variables来指定已经执行的初始滚动(scrollIsRequired)。 当最后一个可见的单元格将显示,比我们可以滚动到所需的单元格,并设置此variables,以避免再次滚动。

 - (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{ //Perform any configuration if (CGRectGetMaxX(collectionView.frame) <= CGRectGetMaxX(cell.frame)) { // Last visible cell if (self.scrollIsRequired) { [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:self.initiallySelectedRepresentativeVerse inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionLeft]; self.scrollIsRequired = NO; } } } 

它为我工作就像一个魅力。

这对我来说是有效的:

我保留了所选索引path的引用,并覆盖了reloadData函数:

 override func reloadData() { super.reloadData() self.selectItem(at: self.selectedIndexPath, animated: false, scrollPosition: UICollectionViewScrollPosition()) } 

我试图使用indexPathForSelectedItems,但它创build集合视图加载无限循环。

创build一个方法,执行select并在调用reload后使用performSelector调用它。

 [self performSelector:@selector(selectIt) withObject:self afterDelay:0.1];