Nested UICollectionViews, AutoLayout and rotation in iOS 8

限于喜欢 提交于 2019-12-02 21:28:22

Answering my own question here - I finally found the solution. For any others who are having troubles with this here is what I did:

The main part lies in putting invalidateLayout and reloadData calls in the right places:

  • Put an invalidateLayout on the base collectionView's layout in the willTransitionToSize function.
  • Put a reloadData on the base collectionView in the completion block of a coordinator animateAlongsideTransition: call in the willTransitionToSize function.
  • Make sure the autolayout constraints for any views in the cells are set right - I connected the cell view with autolayout constraints to the cell's content view in code.
  • In case you overwrote the prepareLayout function of the collection view layout, make sure the pre-calculated cell sizes use the right width, I used a wrong width here which lead to some additional problems.
Scott Cheezem

Thanks to TheEye. I wanted to add this as a comment to their response, but apparently I don't have enough Karma (yet), So consider this an addendum.

I was having the same problem, however the cells in my uicollectionview have an "expanded state" when selected. if the user rotates the device and we call [self.collectionview reloadData], any cells that are expanded will lose their state. You can optionally call performBatchUpdates and force the collection view to layout without losing the state of any cell

-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
[self.collectionView.collectionViewLayout invalidateLayout];

[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {

} completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
    //[self.collectionView reloadData];//this works but reloading the view collapses any expanded cells.       
    [self.collectionView performBatchUpdates:nil completion:nil];       
}];  
}
Seb

TheKey's response is correct. However, instead of reloading the data, you may just call

UICollectionView.collectionViewLayout:finalizeCollectionViewUpdates()

Example:

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

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()
}

I too had the same problem, with the other answers I found that the layout was getting letterboxed. I got closer to what I wanted with this:

 override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: nil, completion:  { context in

            self.collectionView?.collectionViewLayout.invalidateLayout()
            self.collectionView?.collectionViewLayout.finalizeCollectionViewUpdates()

        })

    }

This has been an ongoing issue in our app but finally I achieved what I believe to be the best and easiest solution so far. Basically you'll need to remove the parent (base) collection view from the superview when device rotates and then add it again to the superview. If you do it properly the system will even animate it for you! Here's an example:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator);

    self.collectionView.removeFromSuperview();
    self.collectionView = self.getAFreshCollectionViewInstance();
    self.setupCollectionViewFrameUsingAutoLayout();
}

As for the data of the collection view, it works just fine by using the existing data source and this is really efficient when data is loaded from the web.

Just in case anyone is looking for a Swift 4 solution:

I had a very similar problem and I found the solution to be a combination of two answers above: use the coordinator animate function to call invalidateLayout() on the top collection view, then, in the completion hander, loop through each cell and call invalidateLayout() on each cell's collection view. I didn't have to maintain selections or expanded views so this worked without having to call reloadData().

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)

    // get the device orientation so we can change the number of rows & columns
    // in landscape and portrait modes
    let orientation = UIDevice.current.orientation

    if orientation.isLandscape {
        self.columns = 4
        self.rows = 3
    } else {
        self.columns = 3
        self.rows = 4
    }

    // invalidate the top collection view inside the coordinator animate function
    // then inside the animation completion handler, we invalidate each cell's colleciton view
    coordinator.animate(alongsideTransition: { (context) in

        self.collectionView.collectionViewLayout.invalidateLayout()

    }) { (context) in

        let cells = self.collectionView.visibleCells

        for cell in cells {
            guard let cell = cell as? MyCollectionViewCell else { continue }
            cell.invalidateLayout()
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!