Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autolayout constraints to set labels horizontally

Tags:

ios

autolayout

I have a bar with two UILabels:

[LeftMsg                          RightMsg]

The rules I want to set are:

  1. RightMsg is always fully visible, right-aligned and takes the room it needs.
  2. LeftMsg is left-aligned and takes the remaining room.

For example, if LeftMsg reads "This very long message does not fit the bar", it must be displayed as follows:

 [The very long message does n... RightMsg]

I set horizontal auto-layout constrants as follows:

LeftMsg.leading = Superview.leading
RightMsg.trailing = Superview.trailing
LeftMsg.trailing <= RightMsg.leading

(If I use equality in the last constraint, XCode tells that there is a content priority ambiguity).

Now it works as follows:

 [The very long message does not fit the...]

that is not what I need.

Can anyone suggest how do I correctly set constraints to achieve what I need?

like image 515
Nick Avatar asked Feb 06 '23 02:02

Nick


1 Answers

I think you can set lower horizontal hugging priority for your left label than that of right message label, while at the same time setting higher horizontal compression resistance priority for right message label than that of left message label.

For example, you can set both Content hugging priority and compression resistance priority for your labels like this.

Left Label : content Hugging priority ( H: 250, V: 251) compression resistance priority ( H: 750, V: 750)

Right Label : content Hugging priority ( H: 251, V: 251) compression resistance priority ( H: 751, V: 750)

You can see more information about content hugging and compression resistance in this tutorial.

like image 177
woogii Avatar answered Feb 13 '23 05:02

woogii