1

I am having a heck of a time getting my UICollectionViewCell height to be dynamic based the content inside (in a UILabel element). I've read all over the place about how this is so much easier to do with iOS 8, but I've now spent way to much time trying to figure this out. Hopefully I'm just missing something small. Hopefully...

I was able to sort of make this work by manually setting the height of each cell using this approach (the sizeForItemAtIndexPath part) - calculating it all out based on the text (sizeToFit), but like I said, I've read over and over that it should be 'magic' with Auto Layout and iOS 8, and I shouldn't have to do all that.

So here's my code in the view controller's cellForItemAtIndexPath method:

var cell:LocationCell = collectionView.dequeueReusableCellWithReuseIdentifier("LocationCell", forIndexPath: indexPath) as LocationCell
let thisLocation = fetchedResultsController.objectAtIndexPath(indexPath) as LocationModel

cell.notesLabel.text = thisLocation.notes
cell.notesLabel.sizeToFit()

return cell

Easy enough? right? But each cell is the same height — doesn't matter what the size is notesLabel. Here's what it looks like on the storyboard:

enter image description here

And in the simulator:

enter image description here

As you can see, the height of the UICollectionViewCell is not changing. I've also tried adding the layout property estimatedItemSize in viewDidLoad, but whatever I put in the estimated size, is how all UICollectionViewCells appear.

I can send a github link of any of this is unclear. Really appreciate the help, this has been bothering me for days!!

Community
  • 1
  • 1
SeeMeCode
  • 1,415
  • 15
  • 19

1 Answers1

0

UIView has sizeThatFits as an extension. I've used it to center-center textfields. The basic concept is to load the view, get the measurements it provides, and then resize/position your containers as you like.

ziligy
  • 1,447
  • 16
  • 10
  • Yeah, that's what I tried, but I have to do a lot of custom work to get the correct height, which according to what I've read you shouldn't have to do on iOS 8 (and shouldn't do with Auto Layout). I read [this article](http://captechconsulting.com/blog/tyler-tillage/ios-8-tutorial-series-auto-sizing-table-cells) earlier – scroll down to 'iOS 8 Magic' and be says 'Auto Layout will happily return this resolved height for you'. But how? – SeeMeCode Dec 10 '14 at 00:05