UICollectionView scrollToItem在iOS中不起作用

Dav*_*d J 1 uiviewcontroller ios swift

我使用的是集合视图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)
}
Run Code Online (Sandbox Code Playgroud)

Vik*_*put 25

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
Run Code Online (Sandbox Code Playgroud)


wot*_*tle 5

您可以尝试viewDidLayoutSubviews在所有表单元格加载后放入应该在其中调用的滚动代码,这意味着您的messages.count应该可以工作。另外,请确保您的收藏夹视图中只有一个部分。

override func viewDidLayoutSubviews
{
    self.scrollToBottom()
}

func scrollToBottom() {
    DispatchQueue.main.async {
        let lastIndex = IndexPath(item: messages.count-1, section: 0)
        self.messagesView.scrollToItem(at: lastIndex, at: .bottom, animated: true)
    }
}
Run Code Online (Sandbox Code Playgroud)