Search code examples
iosswiftuicollectionviewuicollectionviewcelluicollectionviewlayout

How to set collectionview cell width based on content?


I have a horizontal scrolling collectionview.The cell contains a label.I want to adjust the cell width based on the content of the label.How can this be achieved??Please help me with this


Solution

  • instead of calling sizeforitem

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
     return CGSize(width: 100, height : 100)
    }
    

    You can set layout properties to auto resizing according to label content

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0
    layout.estimatedItemSize = CGSize(width: 100, height: 30)