I want to implement a TableView with a Custom TableViewCell showing an image.
To make this simple, I simply put a UIImageView inside a tableviewcell using autolayout
If you want the UIImageView to tell the UITableView how tall it needs to be, then you need to configure the table view to enable automatic row calculation. You do this by setting estimatedRowHeight to a fixed positive value and setting rowHeight to UIViewAutomaticDimension. That's part one.
Now you need to configure the UIImageView to request a height based on the width which the table view requires and on the aspect ratio of the image. This will be part two.
First, set the contentMode to .AspectFit. This will cause the view to resize the appearance of the image based on whatever dimensions it takes. However, this still doesn't cause it to request the needed height with auto layout. Instead, it will request the height of the intrinsicContentSize, which may be quite different from the resized image. So, second, add a constraint to the UIImageView that is of the form width = height * multiplier, where the multiplier is based on the aspect ratio of the image itself.
Now the table view will require the correct width, the contentMode mechanism will ensure the image is resized correctly without distortion, and the aspect ration constraint will ensure that the image view requires the correct height via auto layout.
This works. The downside of it is that you will need to update the aspect ratio constraint every time you assign a new image to the image view, which could be quite often if the image view is in a cell that's getting re-used.
An alternative approach is to add only a height constraint and update it in the layoutSubviews of a view containing the image view. This has better performance but worse code modularity.