首页 > 解决方案 > 更新 UICollectionView 大小的奇怪问题

问题描述

我有一个 UICollectionView,它的初始高度是 50。当我知道单元格的大小时,我想更新它。对于我所做的:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    let categoriesCount = 16
    let numberOfItemsInRow = 3
    let numberOfRows = ceil(CGFloat(categoriesCount) / CGFloat(numberOfItemsInRow))

    let newHeight = (numberOfRows * cell.frame.size.height)

    collectionHeight.constant = newHeight
    collectionView.collectionViewLayout.invalidateLayout()
}

但是尽管调用invalidateLayout了 - collectionView 的高度保持不变 - 50。

但是当我切换屏幕时,当我第二次使用 UICollectionView 打开该屏幕时,它会显示正确的高度。

我做错了什么,如何更新 UICollectionView 的高度?

我什至尝试过collectionView.updateConstraints()collectionView.collectionViewLayout.invalidateLayout但仍然没有运气

更新

我也试过

collectionView.layoutIfNeeded()
self.superview?.layoutIfNeeded()

但没有结果。

标签: iosswiftuicollectionview

解决方案


为此,您可能必须调用该self.view.layoutIfNeeded()方法来强制视图更新其布局。

根据文档

...此方法从根开始布置视图子树。

因此,更新您的视图

有关更多信息,您可以阅读线程,您可以在其中挑选一些零碎的内容添加到您的解决方案中。


推荐阅读