Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Layout to dynamically size uilabel width

So I have two UILabels side by side in Storyboard. The second label should butt up against the right edge of the first one (trailing constraint of 1), but I also need the first label (the one on the left) to set it's width equal to it's content size unless it hits a max width. Visually:


|Label one text| |Label two text|


And I need the following constraints:

1) Label one should resize width wise unless it hits a max size.

2) Label two should always be butted up against the right edge of label one

How do I set this up in Storyboard?

like image 904
Msencenb Avatar asked Dec 27 '13 09:12

Msencenb


People also ask

Does UIImageView have intrinsic content size?

Here is the essential problem: the only way in which UIImageView interacts with Auto Layout is via its intrinsicContentSize property. That property provides the intrinsic size of the image itself, and nothing more.

What is translatesAutoresizingMaskIntoConstraints?

translatesAutoresizingMaskIntoConstraints. A Boolean value that determines whether the view's autoresizing mask is translated into Auto Layout constraints.

What is Nslayoutconstraint?

The relationship between two user interface objects that must be satisfied by the constraint-based layout system.


2 Answers

  1. Create the 1 point horizontal space between the labels: Control-drag from label2 to label1. Choose Horizontal Spacing from the pop-up. Double click the constraint. Change the constant to 1.
  2. Give label1 a max width: Select label1. Go to the top menu bar, select Editor > Pin > Width. Double click the constraint. Change the relationship to <= and change the constant to the max width.
  3. Vertically align the labels: Select both labels. Go to the top menu bar, select Editor > Align > Vertical Centers.
  4. You still need to set constraints that define how your labels are positioned in their container view. I leave that up to you. I pinned label1 32 points from the left edge of the root view and 34 points from top layout guide.
  5. Update the frames of the labels so they reflect the above constraints: Go to the menu bar in the lower right-hand corner of the canvas. Tap the "Resolve Auto Layout Issues" Tie-Fighter button. Select "Update All Frames…" in the pop-up.

Note: Notice that I did not have to create constraints to make label1's width reflect its content size. The content sizing constraints are generated automatically.

enter image description here

like image 63
bilobatum Avatar answered Oct 07 '22 07:10

bilobatum


Please refer below constraints to Set UIlabel and UIButton flexible width;

Set UIlabel and UIButton flexible width according to text using xib autolayout

like image 22
Harshal Wani Avatar answered Oct 07 '22 07:10

Harshal Wani