iOS 7 Dynamic Table Cell Height…For Cheaters

Dynamic table cell sizing in iOS is a pain and always has been.

With iOS 7, it has gotten even worse. The once useful “sizeWithFont” method has been deprecated and it has now been replaced with a much more cumbersome, difficult and broken (in regards to use with table views) method “boundingRectWithSize.”

There are a few possible ways to deal with this situation: You can (a) use the above GitHub link which may not work in all situations (I know because I have encountered several of them) (b) find another similar solution someplace on StackOverflow which may also not work or (c) cheat by hacking something together.

After spending three days attempting to find / scouring StackOverflow for an actual solution for dynamically sizing a table cell which contained multiple sub-views along with several dynamically sized labels and images I finally caved and went with option (c): I cheated.

The funny thing is that I had a decent working solution in seconds compared to the hours I had previously spent attempting to measure the actual size of several AutoLayout sized sub-components of various dimensions.

The cheat goes like this: You manually calculate the height of a label by counting the number of characters in the string, dividing by the number of characters required to fill a line to get the number of lines in the string and then multiplying it by the height of your font to arrive at a height. It works. I’m not proud of it but it is a very fast way of solving this annoying issue.

 
UXRDynamicCell *cell = [UXRDynamicCell cellForTableView:tableView];
UXRLabel *contentLabel = cell.contentLabel;
UXRModelObject *model = (UXRModelObject*)[self.dataSource objectAtIndex:indexPath.row];
NSString *text = [model contentText];
CGFloat lineHeight = contentLabel.font.lineHeight;
CGFloat lines = (text.length / 55.0f) * lineHeight;
CGFloat height = lines + 75.0f; //adding some padding
return height;