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
}
Author by
Sajib Ghosh
Updated on August 22, 2022Comments
-
Sajib Ghosh over 1 year
I have a
UIcollectionview
. There are some cells of the Collectionview. Inside thatCollectionviewCell
there is a textview. The textview's content is dynamic. So the cell height should be dynamic.How to do that?
-
Sajib Ghosh over 7 yearsThanks! 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 over 7 yearsThanks! 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 over 7 yearsIf textView use different font and size you must add 'NSFontAttributeName' to 'NSAttributedString' to calculate correct size