【问题标题】:UICollectionView scrollToItem Not Working in iOS 14UICollectionView scrollToItem 在 iOS 14 中不起作用
【发布时间】:2018-10-18 14:47:06
【问题描述】:

我正在使用集合视图 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)
}

【问题讨论】:

  • 可能在调用scrollToItem 时,集合视图还没有加载数据。
  • 在该代码处放置一个断点并查看 lastIndex 的值。正如@mag_zbc 所说,最有可能在调用该代码时(特别是如果这是第一次出现视图。tableview 可能尚未完全加载。此外,在加载完整表后将应用程序置于后台,并且然后重新打开它。这将导致 viewWillAppear 再次触发,但 tableview 将完全加载,您应该滚动到该项目。如果是这种情况,您需要在 viewWillAppear 以外的地方触发滚动。
  • 我也考虑过这些选项。我什至输入了无效的行,它崩溃了,给出了关于项目数和特定行号无效的特定错误。所以我知道它正在被调用和处理。从断点调试显示数据已加载(至少它准确地知道项目数)。 lastIndex 是准确的。如果我将“1”添加到 lastIndex(这将是无效的),它应该会崩溃。

标签: ios swift uiviewcontroller


【解决方案1】:

Swift 5 / iOS 15

我遇到了同样的问题,所以我尝试了这个单行代码并完成了它。

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

【讨论】:

    【解决方案2】:

    UICollection 视图在 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
    

    【讨论】:

    • 谢谢!它有帮助
    • 该死!!奇迹般有效!谢谢!
    • 非常感谢!
    • 这应该标记为答案,这个bug在iOS 15中仍然存在,但是上面的修复解决了它。
    【解决方案3】:

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

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

    【讨论】:

    • 效果很好!谢谢!
    猜你喜欢
    • 2018-11-29
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2020-10-27
    相关资源
    最近更新 更多