0

I'm trying to make table view with two labels and an image in the middle. The image is fetched asynchronously from the web, and after it is fetched I want to make the UIImageView's frame to fit the size of the image, and fit the table view's width. I have set autolayout: for each label and for image only top, bottom, leading and trailing space, no height constraint.

enter image description here

I've set rowHeight and estimatedRowHeight in the controller:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 333.0

After the images are fetched, extra padding appers above and below the image (I've se the background color of image view to red, to clearly see it):

enter image description here

Could you help me so that there's no extra padding in the image view, but it fits the size of the image?

jonaszmclaren
  • 2,459
  • 20
  • 30
  • Have you tried to call the `layoutIfNeeded` method from UIView class? – Nicholas Allio Apr 29 '17 at 15:45
  • Yes, I tried it. – jonaszmclaren Apr 29 '17 at 16:59
  • If your constraints are setup correctly, auto-layout will handle the sizing of the rows. But, `UIImageView` does *not* auto-size to a scaled image... your code needs to change the Height constraint of your image view to match the scaled height of the image after it is downloaded. – DonMag Apr 29 '17 at 17:48

2 Answers2

1

There are two possibility you can go with:

  1. Get width and height from server and calculate total height of cell according to width of table and label height.

  2. Also, you can have a array for height of cells, where you have to store height of cell manually on every image download. and reload that particular cell on image download.

  • Isn't there some solution based on Auto Layout? – jonaszmclaren Apr 29 '17 at 17:01
  • I tried this solution, it kinda works, at the beginning some UIViews' heights are too big, but after scrolling down and up it fixes and everything looks ok. That's weird :) – jonaszmclaren Apr 30 '17 at 17:26
  • unfortunately there is no Auto Layout solution for this situation. I personally use case 1 whenever possible. and yeah you can try "reloadRowsAtIndexPaths" to get rid of big heights without scrolling manually. – Parth Patoliya May 01 '17 at 11:27
  • Thanks a lot for your help. However, reloading rows somehow has no influence on the layout, only after manual scrolling it is better... – jonaszmclaren May 02 '17 at 12:37
1

Kindly check the UIImageView's content mode

VIP-DEV
  • 221
  • 1
  • 6