I’m trying to set the height of a UITableViewCell based on some dynamic content. I know you can “set” the height via the heightForRowAtIndexPath delegate method in your view controller, but… I can’t do that!
The problem is that the height of the cell isn’t known until cellForRowAtIndexPath is called, and heightForRowAtIndexPath is called before cellForRowAtIndexPath.
So, I need to somehow either reverse the order in which these two methods are called, or find another way to set the cell height.
Any ideas?
Sorry – there’s no built-in way to reverse those methods or anything similar. One of the reasons is that a table view can want to know the height of a row for a number of reasons, not all of which include displaying a cell –
-tableView:heightForRowAtIndexPath:might get called several times, or-tableView:cellForRowAtIndexPath:might not get called at all following a call to the height method.What you can do is find another way to compute the appropriate height ahead of time, cache it, and rely on that cached value for
-tableView:heightForRowAtIndexPath:. I’ve managed to do something similar by constructing a “dummy” UITableViewCell instance, keeping it out of the normal reuse queue, and just using it for layout and height-determination purposes. Such a solution would go something like this:-tableView:heightForRowAtIndexPath:.-tableView:heightForRowAtIndexPath:is called.-tableView:cellForRowAtIndexPath:.Depending on the content of your cell and the complexity of the phrase “lay it out” in your use case, this may incur a reasonable performance hit as you calculate the first several heights, or as your users scroll your table view rapidly. However, as your cache warms up, you should be computing fewer and fewer heights as your app continues to run.
One last point: remember that for cells with default heights (which may or may not appear in your table), you can early-out by returning
tableView.rowHeight, rather than computing the default height every time it appears. This can ease the computation burden of the above approach somewhat.