Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollToItemAtIndexPath not working properly

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?

like image 753
codingPanda Avatar asked Jan 07 '14 16:01

codingPanda


1 Answers

I have the exact same problem on iOS 6 and it's fixed on iOS 7. Here is the 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];
}
like image 135
PokerIncome.com Avatar answered Oct 20 '22 00:10

PokerIncome.com