简体   繁体   中英

Swift: Collection View not adjusting correctly to change in size

I have a collection view with 6 elements that should be laid out with 3 rows and 2 columns. I use the following code to achieve this:

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)
}

In viewDidLoad:

 override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.dataSource = self
    collectionView.delegate = self

    flowLayout.scrollDirection = .horizontal
    flowLayout.minimumLineSpacing = 5
    flowLayout.minimumInteritemSpacing = 5

This produces a collection view that looks like this which is perfect:

This is the desired output

However when I situationally hide a view below the collection view before the view is loaded and adjust the size of it(making it 50 pts taller in height), then the output changes to the following (see image) with cells 4 & 5 off the screen unless scrolled to, only 2 rows instead of 3 and a large gap between rows:

Collection view appearance when adjusted to account for hidden view

To situationally hide the view in viewWillAppear I added the following:

 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()
    } 
}

This code tests if testVariable is true, and if it is hides the bottomView and makes the collectionView 50 pts larger to fill the space. I added this code in viewWillAppear in the hope that collectionViewLayout would account for the extra 50 pts of height and adjust according, but it doesnt.

You need to invalidate the layout. It does not do so on its own. Call invalidateLayout() on the flow layout after your call to layoutIfNeeded().

flowLayout.invalidateLayout()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM