2014-01-07 28 views
8

我試圖使用UICollectionView實現照片庫。該設置與此tutorial中的設置類似:單元格與收藏視圖一樣大,因此您一次只能看到一張圖片。分頁已啓用,因此您可以逐張瀏覽圖片。目前爲止一切正常。scrollToItemAtIndexPath無法正常工作

我還想在設備旋轉到橫向時保持該設置。它在細胞/圖像大小方面工作良好。但是像上面教程中所描述的那樣,收藏視圖會旋轉到兩張圖片之間的某個奇怪位置。

我的目標是讓旋轉後顯示旋轉後的同一單元格的集合視圖。就像在這post

我試圖解決這個問題:

旋轉之前,我目前可見項目的indexpath保存財產,像這樣:

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation  duration:(NSTimeInterval)duration { 
    NSArray *visibleItems = [self.galleryCollectionView indexPathsForVisibleItems]; 
    self.currentIndexPath = [visibleItems lastObject]; 
    [self.galleryCollectionView.collectionViewLayout invalidateLayout]; 
} 

和旋轉後,我試圖滾動到該項目如下:

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { 
[self.galleryCollectionView scrollToItemAtIndexPath:self.currentIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES]; 
} 

不幸的是,這只是爲前兩項中的收集,如果我滾動讓我們說第五個項目,並旋轉設備它旋轉到一些奇怪的細胞之間的位置再次。

任何想法我做錯了什麼?

+0

我沒有一個想法是什麼不正常的解決方法對你來說,對我來說它似乎應該起作用,但是我想推薦你使用一個現成的庫來顯示一個照片庫,因爲它有這樣一個常見的任務,並且有這麼好的代碼,並且根據需要折射它。我已經完成了許多項目,包括一個畫廊,並且對人們經常使用的「經過強化的」代碼進行重構通常是時間有效的,例如MWPhotoBrowser –

+0

您是否找到了解決問題的方法? –

+0

我在iOS 6上有完全相同的問題,但它已在iOS 7中修復。 –

回答

2

我在iOS 6完全一樣的問題,它是固定在iOS 7,下面是對我的作品的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]; 
}