How to make UICollectionview cell height dynamic?

10,610

Solution 1

1-Add UICollectionViewDelegateFlowLayout protocol.
2-Conform to protocol by implement the sizeForItemAtIndexPath method in your ViewController.
3-Use the index of the cell to get the text you have and calculate the height and width of it.

class ViewController: UIViewController,UICollectionViewDelegateFlowLayout{

  func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
     let constraintRect = CGSize(width: self.view.frame.size.width, height: CGFloat.max)
     let data = myTextArray[indexpath.row];
     let boundingBox = data.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont(name: Constants.strings.fontName, size: 30)!], context: nil)
     return CGSizeMake(boundingBox.width, boundingBox.height); //(width,hight)
  }

}

Solution 2

Use NSAttributedString in sizeForItemAtIndexPath to calculate rect for the height and width:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let attString = NSAttributedString(string: self.rows[indexPath.row], attributes: [NSFontAttributeName: UIFont.systemFontOfSize(15.0)])
    var r: CGRect = attString.boundingRectWithSize(CGSizeMake(self.collectionView.bounds.size.width, CGFLOAT_MAX), options: .UsesLineFragmentOrigin, context: nil)

    return r.size

}
Share:
10,610
Sajib Ghosh
Author by

Sajib Ghosh

Updated on August 22, 2022

Comments

  • Sajib Ghosh
    Sajib Ghosh over 1 year

    I have a UIcollectionview. There are some cells of the Collectionview. Inside that CollectionviewCell there is a textview. The textview's content is dynamic. So the cell height should be dynamic.

    How to do that?

  • Sajib Ghosh
    Sajib Ghosh over 7 years
    Thanks! But the last cell is behaving differently. All the cells are drawn as expected but the leading of the last cell is more than the others cell. Any suggestion?
  • Sajib Ghosh
    Sajib Ghosh over 7 years
    Thanks! But the last cell is behaving differently. All the cells are drawn as expected but the leading of the last cell is more than the others cell. Any suggestion?
  • Ali Baqbani
    Ali Baqbani over 7 years
    If textView use different font and size you must add 'NSFontAttributeName' to 'NSAttributedString' to calculate correct size