I'm trying to implement a photo gallery using a UICollectionView
. The setup is similar to the one in this tutorial: The cells are as big as the collection view, so you'd see one picture at a time. Paging is enabled, so you scroll through the gallery picture by picture. Everything is working fine so far.
I also want to keep that setup when the device is rotated to landscape. It is working fine regarding the cell/image size. But like it is described in the aforementioned tutorial the collection view is rotated to some strange position between two pictures.
My goal is to get the collection view to display the same cell after the rotation as it displayed before the rotation. Just like in this post.
My attempt to solve this issue:
Before the rotation I save the indexpath
of the current visible item to property like so:
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
NSArray *visibleItems = [self.galleryCollectionView indexPathsForVisibleItems];
self.currentIndexPath = [visibleItems lastObject];
[self.galleryCollectionView.collectionViewLayout invalidateLayout];
}
And after the rotation I try to scroll to that item like so:
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[self.galleryCollectionView scrollToItemAtIndexPath:self.currentIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
Unfortunately this is only working for the first two items in the collection, if I scroll to let's say the fifth item and rotate the device it's rotating to some strange in-between-cells-position again.
Any ideas what I'm doing wrong?