Search code examples
iosswiftxcodeuitableviewuitableviewautomaticdimension

Self-sizing tableview cell with only imageView


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


Solution

  • 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