Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly Size UILabel inside UIScrollView using Interface Builder and Autolayout?

I've created a simple view setup in interface builder. Here's how it looks:

IB View Layout

The view hierarchy is simply:

view
- scrollView
-- label

The scroll view is shown with grey background anchored to its super view top, leading, trailing, and bottom with constraints of 0.

The label is shown with yellow background and has constraints as shown. Additionally, the label has content hugging priority of 1000 for both horizontal and vertical, and it has content compression resistance priority of 1000 for both horizontal and vertical.

In portrait orientation, the label is sized correctly:

Portrait Orientation Screenshot

In landscape orientation, however, the label is not sized correctly horizontally (I intended for the label to fill the width of the screen, less constraint insets as shown):

Landscape Orientation Screenshot

How can I get this label to size correctly horizontally in landscape orientation?

like image 672
JRG-Developer Avatar asked May 12 '14 19:05

JRG-Developer


1 Answers

There is one solution for you.

1. Add your UIScrollView to container (UIView) with zero constraints: enter image description here

enter image description here

2. Add constraints for Label: top, bottom, leading, trailing spaces = 20.

3. Add constraint: label.width = container.width - 40

  • For this, select label in the view structure tree, tap ctrl and pull to container. And select Equal Widths.

enter image description here

  • Then select the created constraint and go to its Utilities and set the constant value to 40.

enter image description here

You should get the following components: enter image description here

Run the app, go to landscape and it works!

enter image description here

Hope it is clear. Best Regards.

like image 55
SoVa_ Avatar answered Oct 21 '22 02:10

SoVa_