Resizable UITableViewCell with variable image and content height
Displaying a variable amount of text in a
tableViewCell is easy. It’s one of those things you learn pretty early. Set the
.automaticDimension, set a top and bottom constraint, set the number of lines to
0, and you’re done.
Trying to incorporate variable text and variable image height? Not quite so easy.
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 things 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. We don’t want to crop our image, but we do want it to display at the correct height. The secret sauce for that is inside our custom
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. The image
src dimensions are passed to our constraint, so the
tableView has what it needs to calculate
aspect. 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
Happy coding! 🚀