title: Swift - UICollectionViewCells with dynamic height
body: <p>I'm developing a chat app and I can't figure out how to make the <code>UICollectionViewCell</code>s' height dynamic, depending on how large the <code>UITextView</code>'s text is.</p>
  <p>Here’s what I've been testing;</p>
  <pre><code>class ViewController: UIViewController {
      @IBOutlet var cv: UICollectionView!
      
      let arr = [&quot;hi hello&quot;, &quot;func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell&quot;, &quot;func collectionView&quot;, &quot;// Do any additional setup after loading the view.&quot;, &quot;extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource&quot;]
      
      override func viewDidLoad() {
          super.viewDidLoad()
          // Do any additional setup after loading the view.
  
          if let flowLayout = cv.collectionViewLayout as? UICollectionViewFlowLayout {
              flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
              flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize
          }
          
          // setup cv constraints here
      }
  
  extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
      func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {
          return arr.count
      }
      
      func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {
          let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;mm&quot;, for: indexPath) as! MessageCollectionViewCell
          cell.setup(text: arr[indexPath.row])
          
          return cell
      }
  }
  </code></pre>
  <p>And here's my cell's code;</p>
  <pre><code>class MessageCollectionViewCell: UICollectionViewCell {
      @IBOutlet var tv: UITextView!
      
      func setup(text: String) {
          tv.text = text
          tv.translatesAutoresizingMaskIntoConstraints = false
          
          NSLayoutConstraint.activate([
              tv.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 0),
              tv.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8),
              tv.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -8),
              tv.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0)
          ])
      }
  }
  </code></pre>
  <p>That's the end result;
  <a href="https://i.stack.imgur.com/lttRb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lttRb.png" alt="screenshot" /></a></p>
  <p>Any idea what I’ve been missing?</p>