Simple Approaches to Auto Layout in iOS Development Part 2

If you are one of the newcomers to this series, you might want to take a look at Part 1 that you can find out where I have started to tell something about Auto Layout. In this part, I will talk about how to add UIScrollView that contains a label and also it is going to have dynamic height by the help of Auto Layout magic!

You can have the following attributes for your view controller when you accomplish the things are mentioned in this article:

  • Without switching Autoshrink on, you can have labels with fixed font size for all devices, regardless of the label’s length.
  • No-coding required for content size of UIScrollView.
  1. Open Xcode (Create New Xcode Project > Single View App)

2. Select Main.Storyboard from Project Navigator

2. Drag out an UIScrollView from the object library and add it to the View Controller:

Optional: You can set a background color to UIScrollView that helps you distinguish it from views that we are going to add.

  • Add Constraints to UIScrollView as follows:
  • You can check constraint from size inspector.

3. Drag out an UIView from the object library and add it to the UIScrollView:

→ Add Constraints to UIView:

  • Firstly, UIView’s trailing, leading bottom and top space to UIScrollView must be set to 0.

4. Add an UILabel to UIView with constraints:

Note: After you add the UILabel, Don’t forget to set Lines to 0 in Attributes Inspector of UILabel. Otherwise, It will be single line UILabel.

4. Add Equal Height and Equal Width constraint to UIView with Safe Area

5. Change equal height priority of UIView to 250.

  • Select Equal Height constraint from Document Outline.
  • You will see detail of the selected constraint in the Size Inspector.
  • Click Priority and select Low (250) from drop-down list.

This is how it looks like those 3 steps:

Now, it is time to try how UIScrollView works with different length of text in UILabel. To get a random text, I generally use Lorem Ipsum Generator.

Check this out!

Click here to see how longer text works with UIScrollView.

Thanks for reading!

Leave a Comment