2016-03-07 55 views
1

我有一個UICollectionView啓用分頁,頁面contentOffset旋轉後未正確調整。如何在旋轉後調整UICollectionView contentOffset?

我overrided以下兩種方法

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { 

collectionView.collectionViewLayout.invalidateLayout() 
} 

override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { 

let width = collectionView.bounds.width 

var frame = collectionView.frame 
frame.origin.x = width * CGFloat(pageControl.currentPage) 
frame.origin.y = 0 

collectionView.scrollRectToVisible(frame, animated: false) 
} 

,但仍然有同樣的問題。

這些更改需要做什麼才能在設備旋轉時正確調整當前頁面的contentOffset?

景觀頁面被正確定位,但是當設備旋轉爲縱向的頁面位置不正確,如下面的圖像

enter image description here

enter image description here

+0

「contentOffset未正確調整」意味着什麼。哪裏不對? – RaffAl

回答

3

我已經解決了這個問題與下一個代碼:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator 
{ 
    CGPoint offset = self.collectionView.contentOffset; 
    CGFloat width = self.collectionView.bounds.size.width; 

    NSInteger index = round(offset.x/width); 
    CGPoint newOffset = CGPointMake(index * size.width, offset.y); 

    [self.collectionView setContentOffset:newOffset animated:NO]; 

    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { 
     [self.collectionView reloadData]; 
     [self.collectionView setContentOffset:newOffset animated:NO]; 
    } completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { 

    }]; 
} 

但考慮到我的照片是sc水平滾動。

在此過渡期間的動畫不是很流暢,但可以接受。如果你想讓它變得優秀,你可以在旋轉之前隱藏一個collectionView,並在屏幕上放置一個帶有當前圖像的圖像視圖。圖像視圖應該旋轉而沒有任何問題。旋轉後,您可以從上方運行適當的代碼,然後從屏幕上移除圖像視圖。我還沒有試圖實現這個想法,但它應該看起來像:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator 
{ 
    CGPoint offset = self.collectionView.contentOffset; 
    CGFloat width = self.collectionView.bounds.size.width; 

    NSInteger index = round(offset.x/width); 
    CGPoint newOffset = CGPointMake(index * size.width, offset.y); 

    //here you should create an image view and place it on the screen 
    //without animation, you should also make constraints for it 
    //you also should hide the collection view 

    [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { 

    } completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) { 
     [self.collectionView reloadData]; 
     [self.collectionView setContentOffset:newOffset animated:NO]; 
     //here you should remove the image view and show the collection view 

    }]; 
} 

抱歉目標C :)。