0
votes

I have a UITableViewCell with multiple pieces of data organized into a vertical stack layout. A few of them are dynamic vertically, one being a UILabel, and one being a UIImageView.

The UIImageView is what I'm having trouble with. I've setup a height constraint with an outlet in my UITableViewCell. The images load async, so the height of the UITableViewCell row will be wrong and we only know the true height of the row once the image is loaded. When I set the constraint to update to appropriate aspect ratio after image is loaded my UITableView gets completely unreliable with images jumping all over the place and formatting not working very well at all.

I have come across another article in StackOverflow that mentioned you should pre-examine the images, get their width and height so we can determine that and set constraints before the image is loaded. This does allow for smooth scrolling.

My question is: Is this the only way? Are there better techniques to using AutoLayout with dynamic image sizes? What would they be?

I've tried calling setNeedsLayout, setNeedsUpdateConstraints, updateConstraintsIfNeeded etc... None of them seem to work.

Any advice?

James

1

1 Answers

2
votes

If you need to predict your cell heights based on image size, then yes, you should pre-examine the images if you want to setup smooth layout with dynamic animation and acceptable scrolling performance.

For example, Pinterest returns image size for requested Pin in API response, because they want you to setup layout before image is fetching asynchronous, actually, they do the same thing in their own iOS Application (you can explore their API here). Example of Pinterest API response with extended information about an image:

root:{} 1 item
 data:{} 5 items
 note:A hardened leather thimble to make stitching leather easier!
 url:https://www.pinterest.com/pin/310959549256036760/
 image:{} 1 item
  original:{} 3 items
   url:https://s-media-cache-ak0.pinimg.com/originals/b2/19/ec/b219ec9b8418233c651de9d17bd00e4a.jpg
   width:640
   height:640

Second option, use "pseudo dynamic height". Main thought, you cell heights are always predictable and pre-calculated, but the image inside the cell has a dynamic size. The best explanation for this kind of solution I recently sew here - Self-sizing Table View Cells.