2013-06-18 48 views
5

我想記住一個項目索引(indexPath.item)在UICollectionView中,並在以後,視圖被替換,然後恢復後,滾動到該記憶的項目。UICollectionView滾動到一個項目

當記憶的項目,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滾動...」不是「[self collectionView滾動...」(請注意self和collectionView之間的點)?看起來像錯誤消息明確指出這個問題 – igrek

回答

2

打印numberofItemsInSection顯示它用於滾動的視圖是陳舊的。刷新視圖後,我使用scrollToItemAtIndexPath,它工作!

10

在嘗試滾動到indexPath之前,您是否撥打[self.collectionView reloadData];

如果你想重新定位indexPath當reloadData完成,將代碼放在這樣一個塊:

[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是有效的,否則你仍然會得到相同的錯誤。

+1

仍然拋出了同樣的錯誤對我來說。 –