Sonnie Hiles
Sonnie Hiles

Reputation: 57

UICollectionView Rotation incorrect layout after rotation

I have a UICollectionView which is exactly 7 cells wide, with no padding in between. I have done this by adding a flow layout with no interim or line spacing and calculating the width as follows:

public func collectionView(
    _ collectionView: UICollectionView, 
    layout collectionViewLayout: UICollectionViewLayout, 
    sizeForItemAt indexPath: IndexPath
) -> CGSize {
    return CGSize(
        width: self.frame.width / CGFloat(7), 
        height: self.frame.height - headerHeight
    )
}

This works fantastically within my iPhone app

enter image description here

where rotation isn't enabled. On iPad, when in portrait mode this works fine.

enter image description here

When rotating, firstly the app doesn't redraw, I've attempted to invalidateLayout however this didn't solve the issue. I have to scroll down and I get the following layout

enter image description here

When I tap a cell it does however redraw, but with padding added pushing the 7th cell down onto another row.

enter image description here

I am looking to redraw the cells so all 7 fit on a single row when the app is either rotated or grown and shrunk in split view. How should I handle this correctly?

Upvotes: 3

Views: 2124

Answers (1)

Nikunj Kumbhani
Nikunj Kumbhani

Reputation: 3924

Add this in your UIViewController class

It will adjust your layout automatically while you change device orientation.

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
        
    guard let columnLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
        return
    }
    columnLayout.invalidateLayout()
}

Upvotes: 4

Related Questions