Setting up constraints to drive UITableViewCell height for UITableViewAutomaticDimension

374 Views Asked by At

I have a custom tableViewCell and I am trying to set up constraints so that I can use tableView.rowHeight = UITableViewAutomaticDimension.

For simplicity sake let’s say I have a uiTableViewCell whose content view contains only UIImageView. The UIImageView is constrained to maintain a certain aspect ratio and is pinned to the left, right, and top of the cell content view. I want my content view’s height to be driven by the height of the UIImage View.

I’ve been trying to solve this by pinning the content view bottom to the bottom of the UIIMage view, but I’m getting 'unable to satisfy all constraints' errors at runtime. What’s the right way to set this up?

1

There are 1 best solutions below

0
On

I know this is kind of late, but i just saw this and hope it helps someone having similar troubles.

Its because you are applying constraints to left and right edge, and is setting the aspect ratio constraints. When this is done, the image view's height is set according to the width, because the image view is pinned to both sides, so the remaining width cannot change, and at the same time, the aspect ratio constraints will come into play.

To solve this issue, what can be done is, remove the constraint to the left or right(keep only one), pin the image view to top and bottom, and set the aspect ratio constraints as well. This will make the width adjust to height and the content view's height gets updated correctly.

If at this point, you get an warning "ambiguous x position for image view", set a width constraint and set its priority to a value less than 1000(which is the priority of all other constraints, I assume).