How do I define the size of a CollectionView on rotate

后端 未结 7 794
被撕碎了的回忆
被撕碎了的回忆 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:09

    The Verified Answer Is Not Efficient

    The Problem - Invalidating the layout in viewWillLayoutSubviews() is heavy work. viewWillLayoutSubviews() gets called multiple times when a ViewController is instantiated.

    My Solution (Swift) - Embed your size manipulation within the UICollectionViewDelegateFlowLayout.

    // Keep a local property that we will always update with the latest 
    // view size.
    var updatedSize: CGSize!
    
    // Use the UICollectionViewDelegateFlowLayout to set the size of our        
    // cells.
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        // We will set our updateSize value if it's nil.
        if updateSize == nil {
            // At this point, the correct ViewController frame is set.
            self.updateSize = self.view.frame.size
        }
    
        // If your collectionView is full screen, you can use the 
        // frame size to judge whether you're in landscape.
        if self.updateSize.width > self.updateSize.height {
            return CGSize(width: 170, 170)
        } else {
            return CGSize(width: 192, 192)
        }
    }
    
    // Finally, update the size of the updateSize property, every time 
    // viewWillTransitionToSize is called.  Then performBatchUpdates to
    // adjust our layout.
    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
        self.updateSize = size
        self.collectionView!.performBatchUpdates(nil, completion: nil)
    }
    

提交回复
热议问题