gpt4 book ai didi

ios - 旋转后如何调整UICollectionView contentOffset?

转载 作者:搜寻专家 更新时间:2023-11-01 06:40:40 28 4
gpt4 key购买 nike

我有一个启用了分页的 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?

横向页面定位正确,但当设备旋转为纵向时,页面位置不正确,如下图所示

enter image description here

enter image description here

最佳答案

我已经用下一段代码解决了这个问题:

- (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 并在屏幕上放置一个带有当前图像的 ImageView 。 ImageView 应该可以毫无问题地旋转。旋转后,您可以从上面运行适当的代码,然后从屏幕上删除 ImageView 。我还没有尝试实现这个想法,但它应该看起来像:

- (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

}];
}

抱歉, objective-c :)。

关于ios - 旋转后如何调整UICollectionView contentOffset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35847278/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com