Ray A.
Ray A.

Reputation: 325

Xcode Auto Layout Vertical Constraints on Table View with Multiple Dynamic Heights

I'm trying to create a UITableViewCell which contains 3 subviews - a button, and two labels. The table view cell should look like this:

Button --Label 1-----------
       --Label 1 continued--

  --Label 2-----------------
  --Label 2 continued ------

Currently, I have button one, with leading, top, width, and height constraints pinning it to the top left. Label 1 has a leading constraint from the Button, top, left and bottom constraints to the content view. Label 1 has number of lines set to 0 and can dynamically expand, and this works so far.

I'm having trouble figuring out how to set constraints for Label 2 so that it is always below Label 1 and can also expand.

I've tried setting a top constraint on Label 2 to the bottom of Label 1, with all other sides pinned to the content view, but this gave the error that height and vertical position were ambiguous. What constraints do I need to add for Label 2?

Upvotes: 0

Views: 468

Answers (2)

Ray A.
Ray A.

Reputation: 325

I've managed to get it to work although I'm still not sure how it works. This is what I did:

Gave Label 1 a top, leading, and trailing constraint to the content view.

Gave Label 2 a bottom, leading, and trailing constraint to the content view.

Gave Label 2 a top constraint to the bottom of Label 1 (Label2.top = Label1.bottom + 3)

Gave Label 1 a bottom constraint to the content view with a relation of greater than (bottomMargin >= Label1.bottom)

This allows both labels to expand, and also works with automatically resizing UITableViewCells using UITableViewAutomaticDimension.

Upvotes: 1

Jose Quintero
Jose Quintero

Reputation: 196

You should check the content hugging priority and content compression resistance priority on the size inspector. this should remove the ambiguity. this happens because auto layout doesn't know which label should grow or shrink in case of being a lack of space.

If that's not the case and you want to keep them both the same size, a equal height constraint from one label to another will do.

Upvotes: 1

Related Questions