UICollectionView Self Sizing Cells with Auto Layout

前端 未结 16 1773
野性不改
野性不改 2020-11-22 05:58

I\'m trying to get self sizing UICollectionViewCells working with Auto Layout, but I can\'t seem to get the cells to size themselves to the content. I\'m having

16条回答
  •  遇见更好的自我
    2020-11-22 06:14

    In iOS10 there is new constant called UICollectionViewFlowLayout.automaticSize (formerly UICollectionViewFlowLayoutAutomaticSize), so instead:

    self.flowLayout.estimatedItemSize = CGSize(width: 100, height: 100)
    

    you can use this:

    self.flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
    

    It has better performance especially when cells in you collection view has constant wid

    Accessing Flow Layout:

    override func viewDidLoad() {
       super.viewDidLoad()
    
       if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
          flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
       }
    }
    

    Swift 5 Updated:

    override func viewDidLoad() {
       super.viewDidLoad()
    
       if let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
          flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        }
    }
    

提交回复
热议问题