简体   繁体   English

UICollectionView scrollToItem 在 iOS 14 中不起作用

[英]UICollectionView scrollToItem Not Working in iOS 14

I'm using a collection view, UICollectionView, and it works absolutely great...except that I cannot scroll to any particular item.我正在使用集合视图 UICollectionView,它工作得非常好……除了我无法滚动到任何特定项目。 It seems to always scroll to the "middle" is my best guess.它似乎总是滚动到“中间”是我最好的猜测。 In any case, whatever I send to scrollToItem seems to have no effect on the scrolling.无论如何,我发送给 scrollToItem 的任何内容似乎都对滚动没有影响。 I've put it in various locations throughout my view controller but with no success.我已将它放在整个视图控制器的各个位置,但没有成功。

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)
}

UICollection View has bug in iOS 14 with scrollToItem . UICollection View 在 iOS 14 中存在带有scrollToItem 的错误。 In iOS 14 it will only work if collection view paging will be desable.在 iOS 14 中,它仅在集合视图分页被禁用时才有效。 So i got a solution if we have to scroll with both manual and programatically.所以如果我们必须手动和以编程方式滚动,我得到了一个解决方案。

Specially for 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

You could try putting the scrolling code in viewDidLayoutSubviews which should get called after all table cells are loaded, which means your messages.count should work.您可以尝试将滚动代码放在viewDidLayoutSubviews ,它应该在加载所有表格单元格后调用,这意味着您的 messages.count 应该可以工作。 Also, make sure you only have a single section in your collection view.此外,请确保您的集合视图中只有一个部分。

override func viewDidLayoutSubviews() {
    super.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)
    }
}

Swift 5 / iOS 15斯威夫特 5 / iOS 15

I was facing the same problem, so I tried this one-line code and get it done.我遇到了同样的问题,所以我尝试了这个单行代码并完成了它。

// here we slect the required cell instead of directly scrolling to the item and both work same. 

self.collectionView.selectItem(at: IndexPath(row: self.index, section: 0), animated: true, scrollPosition: .left)

This is what worked for me, in case you want paging enabled:如果您希望启用分页,这对我有用:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    collectionView.isPagingEnabled = false
    collectionView.scrollToItem(
        at: IndexPath(item: 1, section: 0),
        at: .centeredVertically,
        animated: false
    )
    collectionView.isPagingEnabled = true
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM