首页 > 解决方案 > UICollectionView scrollToItem 在 iOS 14 中不起作用

问题描述

我正在使用集合视图 UICollectionView,它工作得非常好……除了我无法滚动到任何特定项目。它似乎总是滚动到“中间”是我最好的猜测。无论如何,我发送给 scrollToItem 的任何内容似乎都对滚动没有影响。我已将它放在整个视图控制器的各个位置,但没有成功。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let lastIndex = IndexPath(row: messages.count-1, section: 0)
    self.messagesView.scrollToItem(at: lastIndex, at: .bottom, animated: true)
}

标签: iosswiftuiviewcontroller

解决方案


UICollection View 在 iOS 14 中带有scrollToItem的错误。在 iOS 14 中,它仅在集合视图分页禁用时才有效。因此,如果我们必须以手动和编程方式滚动,我得到了一个解决方案。

特别适用于 iOS 14 及更高版本

  self.collView.isPagingEnabled = false
  self.collView.scrollToItem(at: IndexPath(item: scrollingIndex, section: 0), at: .left, animated: true)
  self.collView.isPagingEnabled = true

推荐阅读