the behavior of the UICollectionViewFlowLayout is not defined, because the cell width is greater than collectionView width

后端 未结 20 2195
温柔的废话
温柔的废话 2020-12-01 01:53

2015-08-18 16:07:51.523 Example[16070:269647] the behavior of the UICollectionViewFlowLayout is not defined because: 2015-08-18 16:07:51.523
Example

20条回答
  •  隐瞒了意图╮
    2020-12-01 02:32

    After doing some experimenting, this seems to also be tied to how you layout your collectionView.

    The tl;dr is: Use AutoLayout, not autoresizingMask.

    So for the core of the problem the best solutions I've found to handle orientation change use the following code, which all makes sense:

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    
        coordinator.animate(alongsideTransition: { (context) in
            self.collectionView.collectionViewLayout.invalidateLayout()
        }, completion: nil)
    }
    

    However, there are still situations where you can get the item size warning. For me it's if I am in landscape in one tab, switch to another tab, rotate to portrait, then return to the previous tab. I tried invalidating layout in willAppear, willLayout, all the usual suspects, but no luck. In fact, even if you call invalidateLayout before super.willAppear() you still get the warning.

    And ultimately, this problem is tied to the size of the collectionView bounds updating before the delegate is asked for the itemSize.

    So with that in mind I tried using AutoLayout instead of collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight], and with that, problem solved! (I use SnapKit to do AutoLayout so that I don't pull my hair out constantly). You also just need to invalidateLayout in viewWillTransition (without the coordinator.animate, so just as you have in your example), and also invalidateLayout at the bottom of viewWillAppear(:). That seems to cover all situations.

    I dont know if you are using autoresizing or not - it would be interesting to know if my theory/solution works for everyone.

提交回复
热议问题