UICollectionViewCell size error in Swift

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

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 application crashes with the error "negative or zero sizes are not supported in the flow layout". However, when I took a step, I found that a crash occurs when initializing a cell variable before the size is determined. Why is initializing my cell variable throwing this type of error?

+3


source to share


1 answer


I found my problem. I used collectionView.dequeueReusableCellWithReuseIdentifier () when in fact it should only be used with the "cellForItemAtIndexPath" delegate method. The following code worked for me:



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
}

      

+5


source







All Articles