Nested UICollectionViews, AutoLayout and rotation in iOS 8

后端 未结 7 1107
青春惊慌失措
青春惊慌失措 2021-02-03 16:20

I started to use AutoLayout for a large project and was positively surprised about it. However, now I have to adjust the project to accommodate for rotation and size classes, an

7条回答
  •  我在风中等你
    2021-02-03 16:34

    Wanted to offer an alternative solution. I didn't like the slight delay in calling either reloadData or performBatchUpdates in the coordinator's animation completion. Both also resulted in AutoLayout warnings.

    Within viewWillTransitionToSize, calling invalidateLayout on all visible nested collection views and finally calling invalidateLayout on the outer/top level collection view.

    My collection view cell which has a child collection view:

    class NestableCollectionViewCell: UICollectionViewCell {
      @IBOutlet weak var collectionView: NestableCollectionView?
    }
    

    Extending UICollectionView to invalidate nested collection views:

    class NestableCollectionView: UICollectionView {
    
      func invalidateNestedCollectionViews(){
        let visibleCellIndexPaths = self.indexPathsForVisibleItems()
        for cellIndex in visibleCellIndexPaths {
          if let nestedCell = self.cellForItemAtIndexPath(cellIndex) as? NestableCollectionViewCell {
            // invalidate any child collection views
            nestedCell.collectionView?.invalidateNestedCollectionViews()
            // finally, invalidate the cell's own collection view
            nestedCell.collectionView?.collectionViewLayout.invalidateLayout()
          }
        }
      }
    }
    

    And, invalidate on willTransitionToSize:

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
      super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
    
      self.collectionView.invalidateNestedCollectionViews()
      self.collectionView.collectionViewLayout.invalidateLayout()
    }
    

提交回复
热议问题