How do I define the size of a CollectionView on rotate

后端 未结 7 786
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 15:26

I have a viewcontroller with 2 CollectionView Controllers.

I would like on rotation that only one of the collection views resize to a custom size while the other re

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 16:01

    With new API since iOS 8 I'm using:

    Swift 3:

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        updateCollectionViewLayout(with: size)
    }
    
    private func updateCollectionViewLayout(with size: CGSize) {
        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.itemSize = (size.width < size.height) ? itemSizeForPortraitMode : itemSizeForLandscapeMode
            layout.invalidateLayout()
        }
    }
    

    Objective-C:

    - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator {
            [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
            [self updateCollectionViewLayoutWithSize:size];
    }
    
    - (void)updateCollectionViewLayoutWithSize:(CGSize)size {
            UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
            layout.itemSize = (size.width < size.height) ? itemSizeForPortraitMode : itemSizeForLandscapeMode;
            [layout invalidateLayout];
    }
    

提交回复
热议问题