2

I'm struggling with the following problem: I have a TableViewController in which every cell has only an imageView. It uses autolayout to cell's contentView's margins and it is set to aspectFit. What I want is the height of cell to size accordingly to the imageView's height. In the first screenshot you see the white spaces at each side of the first image and at the top (and also the bottom - second screenshot) of the second image.

Note: my images' aspect ratio is variable.

I've already set this with no luck:

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 300

Also this in cellForRowAt:

cell.setNeedsLayout()
cell.layoutIfNeeded()

Any advice is well received.

Thank you.

Images with aspect fill here

The constraints

Daniel Z.
  • 458
  • 1
  • 3
  • 23
  • what all autolayout constraints you are setting for the image view on the cell. please add your xib file image also. – vivekDas Aug 01 '18 at 11:41

2 Answers2

0

You need to create these constraints , aspect ratio here is 3:1 you can change it according to yours , also the real image should have same aspect to stretch completely as you set contentMode to aspectFit

enter image description here

Edit:

If the aspect is variable then you need these constraints

enter image description here

then hook the height constraint and do this in cellForRowAt after you download / get from cache

cell.imageHeight.constant = imageRealHeight * imageCellWidth / imageRealWidth
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

This is due to the way the image view returns it's intrinsicContentSize. I currently believe this is a bug and should be changed. I have raised a radar for this.

When you put an image into an image view with .scaleAspectFit and with a constraint on one dimension (width or height).

Then it will scale the image down.

So if you start with an image of 300x300 and put it into an image view with a width constraint of 100 then you will get an image view that is 100 points wide.

However, the image view uses the unscaled image for the intrinsicContentSize and so it will want to be 300 points high.

This is the problem you are facing now.

The only fix for this currently is to calculate the aspect ratio of the image and manually set that as a constraint on the image view.

So you might have a line like this...

imageView.image = theImage

You can add to that to add an aspect ratio constraint...

imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor, multiplier: image.size.height / image.size.width).isActive = true

Of course, you will also need to remove any constraints added already. Or possibly create the constraint as a property of the cell etc...

Fogmeister
  • 76,236
  • 42
  • 207
  • 306