Search code examples
iosswiftautolayoutuistackview

AutoLayout: Issue with scaling UIImageView in UIStackView/UITableViewCell


I have a UITableViewCell that contains a UIStackView with views stacked vertically. I have set UITableViewAutomaticDimension as the UITableView's row height and estimated height. One of the subviews of the UIStackView contains two UIImageViews like this:

enter image description here

The little one is avatarImageView and the bigger is messageImageView. Here are the constraints:

avatarImageView:

enter image description here

messageImageView:

enter image description here

Then, I'm trying in cellForRowAt's delegate method to update the height of the messageImageView to match the image scale (and I let a width of 200px for the image view).

let ratio = image.size.width / image.size.height
cell.messageImageViewHeightConstraint?.constant = 200 * ratio

I'm trying to use this image for example:

enter image description here

But it doesn't work at all, the image takes too much space instead and for some reason the avatar image view ends up being hidden (the cell is surrounded in red, above it is a cell with only text that works fine) :

enter image description here

So what am I missing here?

Thanks for your help!


Solution

  • Your ratio is inverted compared to how you are using it:

    The easiest fix is to divide by the ratio instead of multiplying by it:

    let ratio = image.size.width / image.size.height
    cell.messageImageViewHeightConstraint?.constant = 200 / ratio
    

    or if you prefer, change the ratio calculation:

    let ratio = image.size.height / image.size.width
    cell.messageImageViewHeightConstraint?.constant = 200 * ratio