liliqui
liliqui

Reputation: 191

Calculate height of collectionViewCell with dynamic height

I have a UICollectionViewCell that has a few multiline labels. The cell is defined inside a nib. I would like to layout the cells underneath each other (like a UITableView), with a margins left and right.

enter image description here

To calculate the height of the cell, I do the following steps in sizeForItemAtIndexPath:

  1. Instantiate a prototype cell
  2. Create and add a temporary width constraint with the desired width (collectionView width minus left and right padding)
  3. Configure the cell with the future content
  4. Call systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) to get the required height

The height calculation seems to be always slightly off though. After further inspection (calling layoutIfNeeded before systemLayoutSizeFittingSize), it seems that the cell already has a width constraint, that is set to the width as layouted in IB.

(
    "<NSAutoresizingMaskLayoutConstraint:0x7f91baf48be0 h=--& v=--& H:[UIView:0x7f91bacb7440(304)]>",
    "<NSLayoutConstraint:0x7f91bacb7f00 H:[UIView:0x7f91bacb7d90(359)]>",
    "<NSLayoutConstraint:0x7f91ba970730 H:[UIView:0x7f91bacb7d90]-(0)-|   (Names: '|':UIView:0x7f91bacb7440 )>",
    "<NSLayoutConstraint:0x7f91ba970780 H:|-(0)-[UIView:0x7f91bacb7d90]   (Names: '|':UIView:0x7f91bacb7440 )>"
)

The cell is layouted with a width of 304pt during design time. The desired width of the cell is 359pt in this case.

enter image description here

Anyone knows whether it's possible to somehow disable the implicit creation of the width constraint by IB? Or is there a better way to achieve a flexible height, fixed left & right margin layout?

This article suggests to keep the size of the collection view to default (10x10), but that would only work with very simple UI and makes using interface builder to see the design kinda moot:

http://corsarus.com/2015/collection-view-with-self-sizing-cells/

Upvotes: 0

Views: 378

Answers (1)

iSashok
iSashok

Reputation: 2446

You need set Content Hugging priority and Content Compression Resistance priority for each label in your cell (vertical) or declare some height constraint for some labels

Upvotes: 1

Related Questions