4

I am trying to adjust the size of each collection view cell according to the length of the label text contained within

func collectionView(collectionView: UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    var size = CGSize()    
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("lessonCell", forIndexPath: indexPath) as UICollectionViewCell
    var label: UILabel = cell.viewWithTag(300) as UILabel
    var labelSize = label.frame.size
    size = labelSize
    return size
}

When running the code, the app crashes with the error 'negative or zero sizes are not supported in the flow layout.' However, when I stepped through, I found that the crash occurs in initializing the cell variable, before the size is even determined. Why would initializing my cell variable throw this type of error?

barrt051
  • 222
  • 3
  • 12

1 Answers1

6

I found my problem. I was using collectionView.dequeueReusableCellWithReuseIdentifier() when in reality this should only be used with the "cellForItemAtIndexPath" delegate method. What worked for me was the following code:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    var size = CGSize(width: 0, height: 0)
    var label = UILabel()
    label.text = category[indexPath.row]
    label.sizeToFit()
    var width = label.frame.width
    size = CGSize(width: (width+20), height: 50)
    return size
}
barrt051
  • 222
  • 3
  • 12
  • I'm getting good results with the sizingCell approach described here: https://stackoverflow.com/a/53786943/1473527 It's more versatile too. – Matt Bearson Sep 12 '19 at 22:41