2016-03-07 58 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 :)。