barrt051
barrt051

Reputation: 242

Error in sizing UICollectionViewCell in Swift

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?

Upvotes: 5

Views: 3990

Answers (1)

barrt051
barrt051

Reputation: 242

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
}

Upvotes: 7

Related Questions