Variable-height rows in UITableView

I am giving the user a view onto a selection of database records. There could be a handful of these, there could be 10,000 of them.

At present I use a UITableView. Cells are therefore created or recycled on demand. When a cell is created, it is displayed with default "empty" contents and it sends a message to the server to request a record. When the record arrives, the cell is then able to change its own contents so that the record appears on the screen.

There are of course various optimisations, such as cancelling a request if the cell goes offscreen before a reply is received; or delaying a request if it looks as if the cell will end up being off the screen once scrolling has stopped.

All this happens with fixed-height cells. Accordingly the UITableView has all the data it needs to work out where every one of the 10,000 cells is.

I now want to extend this to variable-height cells. That is: cells whose height depends on the content received from the database.

Accordingly, when a cell receives its data it may find itself having to change its own size.

Is this structure practicable with UITableView?

Answered by Frameworks Engineer in 892405022

Yes!

Set the table view's selfSizingInvalidation property to achieve this.

If your cells are sized with Auto Layout, set selfSizingInvalidation to .enabledIncludingConstraints. When you update the contents of the cell, the table view will resize the cell automatically.

If you're using manual layout inside your cells, set selfSizingInvalidation to .enabled, and call invalidateIntrinsicContentSize() on the cell when its contents change. Note you also need to implement sizeThatFits on your cell or its content view and calculate the desired size with this approach.

You can find more information about this property, including a WWDC, video here!

Yes!

Set the table view's selfSizingInvalidation property to achieve this.

If your cells are sized with Auto Layout, set selfSizingInvalidation to .enabledIncludingConstraints. When you update the contents of the cell, the table view will resize the cell automatically.

If you're using manual layout inside your cells, set selfSizingInvalidation to .enabled, and call invalidateIntrinsicContentSize() on the cell when its contents change. Note you also need to implement sizeThatFits on your cell or its content view and calculate the desired size with this approach.

You can find more information about this property, including a WWDC, video here!

Thank you! I will look into this. I am not using Auto Layout, so it is good to know the alternative approach.

I can imagine that in the course of handling some kinds of scroll gestures, UITableView needs to know the size of cells that don't yet exist. Otherwise one couldn't scroll a tenth of the way down a 10,000-row list without explicitly creating 1,000 cells.

Is this the sort of area where estimatedRowHeight comes in?

Variable-height rows in UITableView
 
 
Q