Search code examples
iosobjective-cuitableviewrubymotion

How to update the heightForRow from UITableViewCell


The way my current design works is I dequeue a cell and give it a story id. In the cell initWithStyle I create mysubView (UILabel), set the autolayout constraints and fire a API request that loads the story title async. Then I set the text for the UILabel.

The problem is - at this point the UITableViewController already calculated the wrong height for the cell because initially the UILabel has no text. The only way how to update it now is by doing

parentTableView.beginUpdates
parentTableView.endUpdates

But it feels wrong because I need to reference the parent UITableView from within the cell and there has to be a better way. Am I missing something? I'm using UITableViewAutomaticDimension by the way for the row height.


Solution

  • I suggest you watch Session 211 of WWDC 2012, Building Concurrent User Interfaces and apply the concepts there. This features cells whose contents are independently queried and rendered.

    The basic concept is as follows:
    1. In tableView:cellForRowAtIndexPath, a cell is instantiated.
    2. In the same method, an operation for retrieving the data to populate the cell is created and stored into a dictionary. A reference to the cell is passed to the operation. The operation has a completion handler that populates the cell and removes the operation from the dictionary.
    3. Before the cell is returned from the method, the operation is added to an operation queue.
    4. In tableView:didEndDisplayingCell:forRowAtIndexPath, operations for cells that have moved off-screen are cancelled and removed from the dictionary.