滚动到UICollectionView中的一个项目

5

我想要记住UICollectionView中一个项目的索引(indexPath.item),在稍后的时间,当视图被替换并恢复后,滚动到已经记住的项目。

在记住项目时,indexPath和indexPath.item如下:

indexPath is: <NSIndexPath 0x1d87b380> 2 indexes [0, 32]
indexPath.item is: 32

当稍后重新计算该项的indexPath时,indexPath和indexPath.item是:

indexPath is: <NSIndexPath 0x1d8877b0> 2 indexes [0, 32]
item is: 32

我尝试使用以下方法滚动到记忆位置:
NSIndexPath *iPath = [NSIndexPath indexPathForItem:i inSection:0];
[self collectionView scrollToItemAtIndexPath:iPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];

我收到了一个错误消息:
attempt to scroll to invalid index path

3
错误信息中是否打印了您试图访问的索引路径?如果是的话,且它是 [section, row] 这样的形式,请尝试使用 NSLog 打印 [self.collectionView numberOfItemsInSection:section]; 并告诉我们。 - micantox
1
谢谢micantox。打印numberofItemsInSection发现用于滚动的视图已经过期。在刷新视图后使用scrollToItemAtIndexPath,它就可以工作了! - kzia
1
你是不是忘记加一个点了?即"[self.collectionView scroll...]"而不是"[self collectionView scroll...]"(请注意在self和collectionView之间加一个点)?看起来错误信息确切地指出了这个问题。 - igrek
@kzia,如果这个问题已经解决,请不要忘记关闭它(或提供并批准一个答案)。 - cmyr
2个回答

12

在尝试滚动到indexPath之前,您是否调用了[self.collectionView reloadData];

如果您想要在reloadData完成后重新定位indexPath,请将代码放入一个块中,例如:

[UIView animateWithDuration:0
        animations: ^{ [self.collectionView reloadData]; }
        completion:^(BOOL finished) {
                      NSIndexPath *iPath = [NSIndexPath indexPathForItem:i inSection:0];
                      [self collectionView scrollToItemAtIndexPath:iPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
 }];

在调用scrollToItemAtIndexPath之前,您还可以检查该部分中项目的数量以确保i是有效的,否则您仍将获得相同的错误。


2

打印numberofItemsInSection发现用于滚动的视图已过期。在刷新视图后使用scrollToItemAtIndexPath,它就正常工作了!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接