Following today's guild, here is the git repo
What we covered:
Introducing to Safe Area - the problem on iPhone x without safe area, and how safe area can solve it
Subview safe area - a guide to help us keep elements on subviews and keep margin from safe area
Select the Subview you wish to have a safe area enabled on, go to size tab and check the option 'Safe Area Layout Guide'.
Now you will see another safe area that related to the subview, that you can have a constraints to
We discover how to support iOS 10 with creating another top constraint with the margin we want, and set the relation to equal-or-bigger with the safe area constraint - priority of 750
1. Set top layout constraint, and make the 'Relation' Grater the or equal.
2. Set another top constraint to safe area, and set the priority to 750.
An elegant solution for the bottom view (it can be top as well), increasing the size of the view on iPhone X, with constraint only - we created constraint from top of the view to safe area bottom instead of changing the size of the view programmatically
Here is a code snippet, creating a button and keep space from top, in iPhone x notch, and in other iPhone's
func createButtonWithConstraint() {
// creating the button
let button = UIButton.init()
button.setTitle("Close", for: .normal)
button.backgroundColor = UIColor.lightGray
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
// add top anchor margin to safe area
if #available(iOS 11.0, *) {
button.topAnchor.constraintEqualToSystemSpacingBelow(view.safeAreaLayoutGuide.topAnchor, multiplier: 1.0).isActive = true
} else {
// Fallback on earlier versions
let top = NSLayoutConstraint.init(item: button, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0)
view.addConstraint(top)
}
// constraint for height, width & leading
let leading = NSLayoutConstraint.init(item: button, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 14)
let height = NSLayoutConstraint.init(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 44)
let width = NSLayoutConstraint.init(item: button, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100)
view.addConstraints([leading, width, height])
}
Thanks for participating, let me know if you have any comments.