Safe Area Insets in Swift
A guide for understanding and using Safe Area Insets in Swift (iOS). Github Repository included.
The following guide walks you through how to gather the safe area insets and apply them to your screens. This process uses TinyConstraints, a library that facilitates NSLayoutConstraints and builds on our existing Open Source Swift starter project.
Please note this tutorial uses the TinyConstraints Swift package, which we added using the Swift Package Manager.
What are Safe Area Insets ?
How to implement the safe area insets in Swift?
Please note that the following step by step tutorial follows the way we created it for our open source Swift starter project.
Step One: Create a static variable
In ViewController.swift under Variables, add a new static variable
static var safeAreaInsets: UIEdgeInsets = .zero
Step Two: Create optional constraints for all your base views
In the case of our starter project, we only have one view customView and so we will create four optional constraints:
- var customViewTopConstraint: NSLayoutConstraint?
- var customViewRightConstraint: NSLayoutConstraint?
- var customViewBottomConstraint: NSLayoutConstraint?
- var customViewLeftConstraint: NSLayoutConstraint?
These are important for when we update the constraints later on.
Step Three: Set the safe area insets
In your ViewController.swift add an override to the viewSafeAreaInsetsDidChange function and set the safeAreaInsets to those of the ViewController. The code is available below.
Please note this function will get called every time they change - future proofing us for changes in orientation.
Step Four: Apply your constraints using the safe area insets
In the ViewController+UI.swift, update the constraints for the customView.
Step Five: Verify
Run your app and see the Safe Area Insets applied as shown by the white area, in the before and after.
How do I update constraints on orientation change ?
We have written a separate walkthrough which describes the steps taken to make the safe area insets for a view update on rotation change. Please click the link below to access it.
Any Questions
We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.