3

I am trying to make my cell height size fit with label. The thing is that the label text is set in the cellForItemAtIndexPath, and if i have understood correct, sizeForItemAtIndexPath runs before the cellForItemAtIndexPath. This is something i have tried so far:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let imageCell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as? CollectionViewCell

        imageCell!.imageText.text = post.text // This set the UICollectionView Cell text

        imageCell!.frame.size.height = (imageCell!.frame.size.height) + (imageCell!.imageText.frame.size.height)

        return imageCell!
    }

I am not using Auto Layout.

enter image description here

Any suggestions why the cell height not changes depending on the label?

Roduck Nickes
  • 1,001
  • 1
  • 12
  • 40

2 Answers2

1

This used to be an annoying problem to solve, but it gets substantially easier if you're able to use Auto Layout. See this answer for a thorough walkthrough.

Community
  • 1
  • 1
TwoStraws
  • 11,965
  • 3
  • 52
  • 69
-1

Even if sizeForItemAtIndexPath runs first, that's the place to set the size of the cell. cellForItemAtIndexPath cannot change the size.

In sizeForItemAtIndexPath you need to find out the image size for each cell, then return that size.

Something like this:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let imageCell = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewCell
    let size = CGSize(width: imageCell.frame.width, height: imageCell.frame.size.height + imageCell.imageText.frame.size.height)
    return size

}
Tim
  • 2,042
  • 1
  • 12
  • 20