ios - ScrollToItemAtIndexPath 有时不起作用

标签 ios swift uicollectionview

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

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

最佳答案

我发现调用 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来等待更新可见单元格,我们可以得到我们滚动到的单元格。

关于ios - ScrollToItemAtIndexPath 有时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36029558/

相关文章:

ios - NSDate:将 UTC 值转换为军事时区值

ios - 在 ContainerView 内的 UICollectionView 中计算单元格宽度

objective-c - UICollectionView 布局间距问题。单元格之间的空间太大

ios - 向 UITableView 添加第二个后退按钮

ios - 在 iOS 的 C 函数中使用 ARC 取消引用指针

swift - 获取扩展名为 String 的枚举索引,

ios - 使用 Swift 创建分页 UICollectionView

ios - 将 MDCAppBarNavigationController 与 Storyboard一起使用

ios - iOS-NSMutableArray是不可变的

ios - 更改条形图设计 [iOS 图表]