Safe Area Layout Guides Tutorial iOS 11 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

7 Oct 2017

Safe Area Layout Guides Tutorial iOS 11

The layout guide representing the portion of your view that is unobscured by bars and other content. In iOS 11, Apple is deprecating the top and bottom layout guides and replacing them with a single safe area layout guide.

Safe Area Layout Guides Tutorial iOS 11

  • Bottom layout guide & top layout guide are deprecated from iOS 11.
  • We can change safeArea layout insets by using a safeAreaInsets property.
  • safeAreaInsetsDidChange() method will call when the safe area of the view changes.
In iPhone X we have to use safe area layout otherwise in landscape mode the top notch will cut some content as below:

iPone X top notch will cut some content in landscape

Safe area layout guide Using Storyboards:

It's easy by using storyboard, just go to storyboard and select any one of controller.

Left side go to File inspector there simple check mark the use Safe Area Layout Guides.

File inspector there simple check mark the use Safe Area Layout Guides.

We can migrate old projects to Safe area layout guide.

The Storyboard automatically replaces the top and bottom layout guides with a safe area and updates the constraints:

Safe area layout guide Programmatically:

Create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors.

Now unless you are targeting iOS 11 only you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions:

Code:

if #available(iOS 11, *) {
    let guide = view.safeAreaLayoutGuide
    label.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
    label.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    label.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
   
} else {
    label.topAnchor.constraint(equalTo: topLayoutGuide.topAnchor).isActive = true
    label.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    label.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}

Conclusion:

  • The safeAreaLayoutGuide is a property of UIView where topLayoutGuide and bottomLayoutGuide are properties of UIViewController
  • The constraintEqualToSystemSpacingBelow method is new in iOS 11 and removes the need to hard code standard spacing. There are also less than and greater than versions. For horizontal spacing there is also constraintEqualToSystemSpacingAfter.
  • We can increase or decrease of safe area size using safeAreaInsets property.

Next Steps :

iOS 11[Swift 4] Navigation Bar With Large Titles and LargeTitleTextAttributes

No comments:

Post a Comment

Post Top Ad