Laying Out Text-Based Content on Your Views - The User Interface - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 3. The User Interface

3.7 Laying Out Text-Based Content on Your Views

Problem

You want to show text-based content to your users and want to lay it out on the screen in the optimal position.

Solution

Use the readableContentGuide property of UIView.

Discussion

The readableContentGuide property of UIView gives you the margins that you need to place your text content on the screen properly. On a typical iPhone 6 screen, this margin is around 20 points on both the left and the right. The top and bottom margins on the same device are usually set near 0. But don’t take these numbers at face value. They might change and you should never think about them as hardcoded values. That is why we should use the readableContentGuide property to place our components correctly on the screen.

There isn’t really so much more to it than that, so let’s just see an example. In this code, I will create a label and stretch it horizontally and vertically to fill the readable section of my view. I will also make sure the top and left positioning of the label is according to the readable section’s guides:

let label = UILabel()

label.translatesAutoresizingMaskIntoConstraints = false

label.backgroundColor = UIColor.greenColor()

label.text = "Hello, World"

label.sizeToFit()

view.addSubview(label)

label.leadingAnchor.constraintEqualToAnchor(

view.readableContentGuide.leadingAnchor).active = true

label.topAnchor.constraintEqualToAnchor(

view.readableContentGuide.topAnchor).active = true

label.trailingAnchor.constraintEqualToAnchor(

view.readableContentGuide.trailingAnchor).active = true

label.bottomAnchor.constraintEqualToAnchor(

view.readableContentGuide.bottomAnchor).active = true

See Also