Resizable UITableViewCell with variable image and content height

Displaying a variable amount of text in a tableViewCell is easy enough. Set the .rowHeight to .automaticDimension, set top and bottom constraints, number of lines to 0, and you’re done.

Trying to incorporate variable text and variable image height will probably test your patience. :)

If you’re like me, you’ll fight with auto-layout for a while, maybe refer to Stack or Medium for some pointers. You might even arrive at something that appears to get it all working correctly. Then you start scrolling, and your UI goes to hell.

Sound familiar? Read on.

• • •

I’m assuming you’ve already set (or know how to set) automaticDimension in your tableView class. So do that, if you haven’t yet. Second, make sure your imageView in the storyboard is set to Aspect Fit. The secret sauce is inside our custom tableViewCell class:

Most of the work is being done in setCustomImage(). Our constraint object is being set on the imageView using the width and height received from our API call. In this case, we’re loading posts from a Facebook Page feed. Image dimensions are passed to our constraint, so the table has what it needs to layout the imageView. Finally, the URL is passed to Kingfisher, so we get a nice async load (and cache). Our textView height is already taken care of with automaticDimension. Neat. Make sure to clear the constraint in prepareForReuse().

Happy coding! 🚀