【问题标题】:ScrollToItemAt in UICollectionView does not workUICollectionView 中的 ScrollToItemAt 不起作用
【发布时间】:2021-09-21 01:47:56
【问题描述】:

我使用 Storyboard (Swift) 中的 UICollectionView 创建了一个水平菜单。将集合滚动到活动单元格时出现问题 - 滚动仅在不更新集合的情况下才能正常工作。而且我需要更新它以显示活动单元格(底部的文本颜色和线条,隐藏在非活动单元格中)。问题的本质在附加到代码的动画中清晰可见。

如何纠正问题并制作真正的工人菜单?

代码 1 滚动是正确的,单元格没有重新加载 gif-demonstration

//1
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

  collectionMenu.isPagingEnabled = false
  collectionMenu.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
  collectionMenu.isPagingEnabled = true

}

代码 2 重新加载单元格,但滚动已损坏 gif-demonstration

//2
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

  collectionMenu.reloadData() //change design active cell
  collectionMenu.isPagingEnabled = false
    collectionMenu.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
    view.layoutIfNeeded()
    collectionMenu.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
  collectionMenu.isPagingEnabled = true

}

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    与其在didSelectItem(at:) 上重新加载collectionView,不如从那里手动更新单元格样式。我认为也不需要从 didSelect 切换 collectionView 上的分页。

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionMenu.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
    
        guard let cell = collectionView.cellForItem(at: indexPath) as? YourCell else { return }
        cell.titleLabel.text = // Your orange colour
    }
    

    您可能还需要像这样覆盖单元格内的prepareForReuse 方法,以防止出现出列问题,例如在错误时间显示文本颜色等。

    class YourCell: UICollectionViewCell {
    
        override func prepareForReuse() {
            super.prepareForReuse()
            
            titleLabel.text = // Your default grey colour
        }
    
    }
    

    【讨论】:

    • 感谢您的回复!我试过这个,但我仍然需要更新集合以获得新的单元格宽度(里面的文本改变了 fat 的字体脚背,因此不适合里面)。使用 reloadItems(at: [indexPath]) 更新孤立的单元格无法正常工作并会中断滚动。如何获得新的单元格宽度或更新集合? (isPagingEnabled - 这个属性有助于将项目准确地对齐在中心,因为有时滚动不是按需要工作的(当我尝试使用 reloadData() 和 layoutIfNeeded() 时)
    猜你喜欢
    • 2014-06-22
    • 2018-03-26
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多