我启用了UICollectionView
分页功能,轮播后页面contentOffset
未正确调整。
我重写了以下两种方法
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?
在横向上页面正确定位,但当设备旋转为纵向时,页面位置不正确,如下图所示
答案 0 :(得分: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) {
}];
}
但考虑到我的照片是水平滚动的。
此过渡期间的动画不是很流畅,但可以接受。如果你想要做得很好,可以在旋转前隐藏一个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:)。