ScrollToItemAtIndexPath有时不起作用

时间:2016-03-16 07:46:49

标签: ios swift uicollectionview

在我的收藏中,UICollectionView个实例中有25个单元格。第一个单元格位于indexPath(0,0),最后一个单元格位于indexPath(0,24)。

无论我从第一个单元格滚动到最后一个单元格还是从最后一个单元格滚动到第一个单元格,目标单元格总是为零,这似乎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}

2 个答案:

答案 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等待更新可见单元格,我们可以获取滚动到的单元格。

答案 1 :(得分:0)

您的indexPath是如何创建的?

您可以尝试以下列方式创建它:

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

应该有用......

相关问题