title: How to approach creating Dynamic UICollectionView Item Sizes?
body: <p>I've been working on this problem for probably 24 hours now and I can't seem to find out how you're intended by Apple to set the dynamic height of a CollectionViewCell.</p>
  
  <p>This is where I'm completely lost:</p>
  
  <p>1.) I need each Cell's frame size in my UICollectionView to be determined by the UILabel's text within each cell. The UILabel's frame is constrained to the edges of the cell, so simply grabbing the UILabel.frame's height gives me the precise value I need.</p>
  
  <p>2.) 1 BIG PROBLEM, the UICollectionView's <code>sizeForItemAtIndexPath</code>'s function is executed first before the UILabels are even populated in the UICollectionView's <code>cellForItemAtIndexPath</code> function.</p>
  
  <p>Below is a hack I've tried which failed misrably:</p>
  
  <pre><code>func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -&gt; UICollectionViewCell {
      let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MsgCell", forIndexPath: indexPath) as! CustomCollectionViewCell
  
      cell.txtLabel.text = dummyChatFeed[indexPath.row].messageBody   
      cell.txtLabel.sizeToFit()
      cell.lineBreakMode = NSLineBreakMode.ByWordWrapping
  
      // store the value of this proper label height back into the array:
      dummyChatFeed[indexPath.row].frameHeight = cell.txtLabel.frame.height
      return cell
  }
  
  func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -&gt; CGSize {
  
      // grab that proper label height again:
      var theHeightThatFits = dummyChatFeed[indexPath.row].frameHeight
  
      return CGSize(width: Double(self.view.frame.width), height: Double(theHeightThatFits))
  }
  </code></pre>
  
  <p>The dummyChatFeed is an NSObject Class which contains only these 4 properties:</p>
  
  <pre><code>var messageBody = ""
  var author = ""
  var frameHeight = CGFloat(0)
  var indexPathRow = 0
  </code></pre>
  
  <p>This solution I've tried barely works, and it's buggy as hell since the height of the Cell depends on the label within it. But what is the best way to go from here?</p>
  
  <p>I thought initially that it's best to keep an array of objects with one property of the object that stores the label text while another property of the object should store the value of the recommended height, but I've just learned the hard way that it would never work.</p>
  
  <p>Am I suppose to programmatically declare a UILabel within my dummyChatFeed and calculate the width and height from there based on text and font?</p>
  
  <p>I need my app to be backwards compatible with iOS 8.4 so I can't use UIStackViews.</p>