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

时间:2017-02-14 14:34:09

标签: ios swift uicollectionview

我有一个包含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

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

This is the desired output

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

Collection view appearance when adjusted to account for hidden view

要在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点高度并根据调整,但它不会。

1 个答案:

答案 0 :(得分:3)

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

flowLayout.invalidateLayout()