ios - UICollectionView 在 iPad 旋转时无法正确适应
问题描述
我正在尝试使用UICollectionView
在 iPhone 上,我希望我的视图堆叠,在 iPad 上,我希望它连续排列 3 个。
这是有效的,但是当我旋转我的 iPad 并再次将其旋转回来时,我的子视图不会返回它们在该旋转中最初所处的位置。
关注 gif 中的 Recognition 项就可以看到行为
这是我的视图控制器
class AdaptiveLayoutCollectionView: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
registerCells()
configureLayout(with: view.bounds.size)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
configureLayout(with: size)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
configureLayout(with: view.bounds.size)
}
final func setLayout(as layout: CollectionViewLayoutOption) {
self.layout = layout
configureLayout(with: view.bounds.size)
}
func registerCells() { /* register cells in super view */ }
private func configureLayout(with size: CGSize) {
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
flowLayout.sectionInset = UIEdgeInsets(top: 8.0, left: 0, bottom: 8.0, right: 0)
if traitCollection.horizontalSizeClass == .regular {
//let minItemWidth: CGFloat = 300
let minItemWidth: CGFloat = size.width / 3
let numberOfCell = size.width / minItemWidth
let width = floor((numberOfCell / floor(numberOfCell)) * minItemWidth)
flowLayout.itemSize = CGSize(width: width, height: 80)
} else {
flowLayout.itemSize = CGSize(width: size.width, height: 80)
}
collectionView.reloadData()
}
}
解决方案
推荐阅读
- function - 如何通过 Dart 中的布尔函数更改整数变量
- r - R - 午夜 POSIXct 至今
- docker - Docker 保持主机名可用,即使容器没有运行
- javascript - 在 VueJS 过滤器组件中编写 Switch 语句的更好选择?
- azure - Azure 数据流交叉联接
- c# - c#编辑php文件中的文本
- cassandra - Cassandra 3.0 一个节点未与 3 节点集群中的其他 2 个节点同步
- sql - 使用过去 6 个月的周数创建表,以及它们各自的月份和年份。SQL 服务器
- javascript - 使用已调用的 javascript 函数打开一个 html 文件
- c# - 如何在 C# 中使用 Task.Delay()?