In iOS 12, when does the UICollectionView layout cells, use autolayout in nib

后端 未结 7 1686
一整个雨季
一整个雨季 2020-11-28 03:08

Same code like this

collectionLayout.estimatedItemSize = CGSize(width: 50, height: 25)
collectionLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize
co         


        
7条回答
  •  半阙折子戏
    2020-11-28 03:34

    I have the same problem, cells use the estimated size (instead of automatic size) until scrolled. The same code built with Xcode 9.x runs perfectly fine on iOS 11 and 12, and built in Xcode 10 it runs correctly on iOS 11 but not iOS 12.

    The only way I’ve found so far to fix this is to invalidate the collection view’s layout either in viewDidAppear, which can cause some jumpiness, or in an async block inside viewWillAppear (not sure how reliable that solution is).

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
        layout?.estimatedItemSize = CGSize(width: 50, height: 50)
        layout?.itemSize = UICollectionViewFlowLayout.automaticSize
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // The following block also "fixes" the problem without jumpiness after the view has already appeared on screen.
        DispatchQueue.main.async {
            self.collectionView.collectionViewLayout.invalidateLayout()
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // The following line makes cells size properly in iOS 12.
        collectionView.collectionViewLayout.invalidateLayout()
    }
    

提交回复
热议问题