DevPrep

All topics › Auto Layout

Self-sizing cells: how do UITableView and UICollectionView compute height?

Middle PRO

The gist

In self-sizing mode the cell's height is set not by the delegate but by Auto Layout. The collection fixes the width (the table's width or the item's width from the layout), asks the cell to compute a fitting size via systemLayoutSizeFitting, and gets the height from the contentView constraints. Until a cell is shown, an estimate is used: it is needed to compute contentSize and the scroll indicator without laying out every cell.

Hence the main requirement: inside contentView you need an unbroken chain of constraints from top to bottom, and multiline labels need numberOfLines = 0 and full horizontal constraints.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store