Swift:集合视图未正确调整以改变大小

我有一个包含6个元素的集合视图,应该用3行和2列进行布局。 我使用以下代码来实现此目的:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let totalWidth = collectionView.bounds.size.width - 12 let totalHeight = collectionView.bounds.size.height - 18 let heightOfView = (totalHeight / 3) let dimensions = CGFloat(Int(totalWidth)) return CGSize(width: dimensions / 2, height: heightOfView) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 6 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(0, 5, 0, 5) } 

在viewDidLoad中:

  override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self flowLayout.scrollDirection = .horizontal flowLayout.minimumLineSpacing = 5 flowLayout.minimumInteritemSpacing = 5 

这会产生一个看起来像这样完美的集合视图:

这是所需的输出

但是,当我在加载视图之前在集合视图下方隐藏视图并调整其大小(使其高度高50磅)时,输出将更改为以下(参见图像),其中单元格4和5关闭屏幕除非滚动到,只有2行而不是3行和行之间的大间隙:

调整时的集合视图外观以考虑隐藏视图

为了在viewWillAppear中情境隐藏视图,我添加了以下内容:

  override func viewWillAppear(_ animated: Bool) { if testVariable == true { bottomView.isHidden = true // make bottomView height = 0 bottomViewHeight.constant = 0 // make collectionView space to the bottom of the view controller 0 collectionToBase.constant = 0 view.layoutIfNeeded() } } 

此代码测试testVariable是否为true,如果它隐藏了bottomView并使collectionView 50 pts更大以填充空间。 我在viewWillAppear中添加了这个代码,希望collectionViewLayout可以计算额外的50点高度并根据调整,但它没有。

您需要使布局无效。 它本身不会这样做。 在调用layoutIfNeeded()之后,在流布局上调用invalidateLayout()。

 flowLayout.invalidateLayout()