Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating UICollectionView on orientation changes

Consider a UICollectionView that has a different number of items and a different layout (ie: spacing) on landscape and portrait orientation.

What needs to be done for these changes to be animated when the device is rotated? I couldn't find any mention of how to handle rotations on the Collection View Programming Guide.

like image 966
hpique Avatar asked Nov 01 '12 16:11

hpique


3 Answers

It's not necessary to reload the collection view's data — invoking [collectionView.collectionViewLayout invalidateLayout] will cause the collection view to update its layout.

Overriding shouldInvalidateLayoutForBoundsChange: to return YES in a UICollectionViewLayout subclass will result in invalidateLayout being called automatically whenever the collection view's bounds change (including when its size changes and when the user scrolls its contents).

like image 89
titaniumdecoy Avatar answered Oct 15 '22 12:10

titaniumdecoy


I had different number of sections based on the orientation, and the auto rotation didn't change it. I had to add a call to the collectionView to reload the data. I'm using a UICollectionViewController, adjust to your own collection view property if you have something else:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(    NSTimeInterval)duration {
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self.collectionView reloadData];
}
like image 25
christophercotton Avatar answered Oct 15 '22 12:10

christophercotton


The quickest way is a mix of all other answers.

just add the following lines in your ViewController :

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    self.mCollectionView.collectionViewLayout.invalidateLayout()
}

You do not need to reloadData.

like image 6
CZ54 Avatar answered Oct 15 '22 12:10

CZ54