1

I have a table view with self-sizing cells where I display an image. The content mode of the image view is AspectFit, so that I can see the whole image in correct aspect ratio. The image view is constrained to the superview, but also has max height constraint.

When I have an image which is re-sized according to the content mode and therefore less high than the original size, I want the height of the image view like the re-sized image and not like the original image.

I have a sample project (see screenshot & download link below) where you see the current behaviour: The yellow and green cells have the correct top and bottom space, the blue cell is 150 pt high but it should be less to have the same top and bottom space. In the screenshot you can see that the extra top and bottom space is just empty.

enter image description here

Here is my sample project (Swift 3):

https://www.dropbox.com/s/16i48qnm54fktdk/Test.zip?dl=0

Does anybody has a clue how to fix this?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Tobi
  • 103
  • 1
  • 1
  • 5

2 Answers2

0

One thing you can do is align the imageViews vertically and horizontally in center of the superView and assign a dummy width and height to it. Make outlets for both width and height constraints inside the cell. You can then resize image to fit the width of screen white maintaining the aspect ratio and set the imageView height and width to be the size of the image. In heightForRowAtIndexPath you will have to set the height of the cell based on the value you get for imageView.size.height after resizing

Edit: In hindsight, this seems like a bit of a workaround, maybe someone else may know a better way.

Rikh
  • 4,078
  • 3
  • 15
  • 35
0

Unfortunately, sizeToFit() doesn't work on UIImageView. However, you can set your testImageViewHeightConstraint to the height of your image.

if let imageHeight = cell.testImageView.image?.size.height, imageHeight < cell.testImageViewHeightConstraint.constant {
    print(imageHeight) // this is not the correct height of your image
    cell.testImageViewHeightConstraint.constant = //your image height
}

BUT, there is no way to get the image height after applying aspectFit. The only way to get it is to implement a custom function by yourself. You can see this post:How to know the image size after applying aspect fit for the image in an UIImageView

You can set your testImageViewHeightConstraint.constant to 50 first, just to make sure my suggestion is working :)

Community
  • 1
  • 1
Dovahkiin
  • 1,239
  • 11
  • 23