Nested UICollectionViews, AutoLayout and rotation in iOS 8

后端 未结 7 981
青春惊慌失措
青春惊慌失措 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条回答
  •  猫巷女王i
    2021-02-03 16:37

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

提交回复
热议问题