UICollectionView Self Sizing Cells with Auto Layout

I’m trying to get self sizing UICollectionViewCells working with Auto Layout, but I can’t seem to get the cells to size themselves to the content. I’m having trouble understanding how the cell’s size is updated from the contents of what’s inside the cell’s contentView.

Here’s the setup I’ve tried:

  • Custom UICollectionViewCell with a UITextView in its contentView.
  • Scrolling for the UITextView is disabled.
  • The contentView’s horizontal constraint is: “H:|[_textView(320)]”, i.e. the UITextView is pinned to the left of the cell with an explicit width of 320.
  • The contentView’s vertical constraint is: “V:|-0-[_textView]”, i.e. the UITextView pinned to the top of the cell.
  • The UITextView has a height constraint set to a constant which the UITextView reports will fit the text.

Here’s what it looks like with the cell background set to red, and the UITextView background set to Blue:
cell background red, UITextView background blue

I put the project that I’ve been playing with on GitHub here.

17 Answers
17

Leave a Comment