首页 > 解决方案 > 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()
    }
}

标签: iosswiftuicollectionviewuicollectionviewlayout

解决方案


推荐阅读