【问题标题】:Height on UICollectionViewCell error when reload重新加载时 UICollectionViewCell 错误的高度
【发布时间】:2018-11-18 21:34:33
【问题描述】:

我将问题作为this question的一个分支

ViewCells 上的自动调整大小非常完美。但是当我重新加载我的 CollectionView 时,高度返回 1。

代码如下。

extension SaleViewController: CollectionViewFlowLayoutDelegate{
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        guard let flowLayout = self.myCollectionView.collectionViewLayout as? CustomLayout else {
            return
        }
        flowLayout.invalidateLayout()
    }

    func height(at indexPath: IndexPath) -> CGFloat {
        guard let cell = self.myCollectionView.cellForItem(at: indexPath) else {
            return 1
        }
        cell.layoutIfNeeded()
        //get calculated cell height
        return cell.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
    }
}

缺少什么或我应该重新考虑什么以保持我的自动高度?

提前致谢。

【问题讨论】:

  • 因此,从这段代码来看,它似乎返回 1,因为它在您传递的 indexPath 中找不到单元格。我建议在return 1 行上放一个断点,并弄清楚为什么这个 indexPath 没有单元格
  • 也许您必须执行self.myCollectionView.reloadData() 才能在访问高度之前重新加载数据。您可以尝试做的另一件事是在func cellForItem(at: IndexPath) -> UICollectionViewCell? 函数中设置高度。要检查的另一件事是通过实现 UICollectionViewDataSource 并在初始化程序中使用 self.datasource = self 来查看您是否正确连接了数据源。
  • 请发布您的自定义布局代码

标签: swift uicollectionviewcell autosize uicollectionviewflowlayout


【解决方案1】:

检查您的 CustomLayout 会有缓存为您的 cell.ex 存储 layoutAttribute : private var cache: [IndexPath : UICollectionViewLayoutAttributes] = [:]

您必须在重新加载之前清除此缓存

guard let flowLayout = self.myCollectionView.collectionViewLayout as? CustomLayout else {
            return
        }

flowLayout.cache.RemoveAll()
flowLayout.delegate = self
CollectionView.reloadData()

【讨论】:

  • 我可以知道你的单元格的布局我的意思是它包含什么,图像,文本等
猜你喜欢
  • 1970-01-01
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多