I am trying to implement a photo gallery using a UICollectionView . The setup is similar to the one in this tutorial : cells are the size of a collection view, so you will see one image at a time. Paging is enabled, so you are viewing the gallery image by image. So far, everything is working fine.
I also want to keep this setting when the device is rotated to landscape. It works great in regards to cell / image size. But, as described in the aforementioned tutorial, the presentation of the collection turns into some strange position between the two pictures.
My goal is to get a collection view in order to display the same cell after rotation, while it is displayed before rotation. As in this post .
My attempt to solve this problem:
Before rotation, I save the indexpath current visible element in the property:
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { NSArray *visibleItems = [self.galleryCollectionView indexPathsForVisibleItems]; self.currentIndexPath = [visibleItems lastObject]; [self.galleryCollectionView.collectionViewLayout invalidateLayout]; }
And after rotation, I will try to scroll this element like this:
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [self.galleryCollectionView scrollToItemAtIndexPath:self.currentIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES]; }
Unfortunately, this only works for the first two elements in the collection, if I scroll to say the fifth element, and rotate the device again, which again rotates to some strange position between the cells.
Any ideas what I'm doing wrong?
ios objective-c uicollectionview
codingPanda
source share