ScrollToItemAtIndexPath not working properly

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?

+8
ios objective-c uicollectionview
source share
1 answer

I have the same problem on iOS 6 and it is fixed on iOS 7. Here is a workaround that works for me for iOS 6.

 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; // workaround iOS 6 collection view rotation bug: UICollectionView is not scrolled to the correct index after rotation [self.collectionView setContentOffset:[self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentPage inSection:0]].frame.origin animated:NO]; } 
+2
source share

All Articles