2016-03-16 48 views
1

在我的集合中,有一个UICollectionView实例,有25个单元。第一个单元位于indexPath(0,0),最后一个单元位于indexPath(0,24)。ScrollToItemAtIndexPath有时不起作用

不管我从第一个单元格滚动到最后一个单元格还是从最后一个单元格滚动到第一个单元格,目标单元格总是为零,这似乎是scrollToItemAtIndexPath函数没有将单元格滚动到可见。

当我从第二个单元格滚动到第一个单元格时,它会很好。

我能做些什么才能在第一个和最后一个之间正确滚动? 我试过layoutIfNeeded,但没什么不同。

这里是我的代码部分:

collection.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredVertically, animated: false) 
    print("indexPath") 
    print(indexPath) 
    guard let senderCell = collection.cellForItemAtIndexPath(indexPath) as? ImageCollectionViewCell else{ 
     print(collection.cellForItemAtIndexPath(indexPath)) 
     return 
    } 

而且在安慰时,安慰:

indexPath 
    <NSIndexPath: 0x79e53110> {length = 2, path = 0 - 24} 
    nil 
    indexPath 
    <NSIndexPath: 0x7b8c2690> {length = 2, path = 0 - 0} 
    nil 
    indexPath 
    <NSIndexPath: 0x79fc48e0> {length = 2, path = 0 - 1} 
    indexPath 
    <NSIndexPath: 0x79eb3950> {length = 2, path = 0 - 0} 

回答

1

我已经想通了,有叫scrollToItemAtIndexPathcollectionView更新新的可见单元格之间的时间间隔。

所以我改变了我的代码如下:

collection.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredVertically, animated: false) 
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(delayTime, dispatch_get_main_queue()) {[unowned self] in 
    guard let senderCell = collection.cellForItemAtIndexPath(indexPath) as? ImageCollectionViewCell else{ 
     print("senderCell no found") 
     return 
    } 
    //Do something with the senderCell 
} 

通过添加delayTime等待更新可见单元格,我们可以得到我们滚动到细胞。

+0

此解决方案效果很好。谢啦。不过,我不得不再次在viewDidLayoutSubviews中调用scrollToItemAtIndexPath,以便单元适合屏幕。对于没有这个的我来说,下一个单元格部分显示。 –

0

如何创建您的indexPath?

您可以尝试的方式来创建它,如:

NSIndexPath* indexPath = [NSIndexPath indexPathForItem:0 inSection:0]; 
NSIndexPath* indexPath = [NSIndexPath indexPathForItem:25 inSection:0]; 

作品是否应...

+0

我的方式和你的一样。不管怎么说,还是要谢谢你。 – LinShiwei