How to use safeAreaLayoutGuide in iOS 10

Issue #98

The safeAreaLayoutGuide was introduced in iOS 11. And it is advised to stop using topLayoutGuide bottomLayoutGuide as these are deprecated.

To use safeAreaLayoutGuide, you need to do iOS version check

1
2
3
4
5
if #available(iOS 11.0, *) {
headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20)
} else {
headerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20)
}

Maybe we can introduce a common property that can be used across many iOS versions, let’s call it compatibleSafeAreaLayoutGuide

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
extension UIView {
/// Use safeAreaLayoutGuide on iOS 11+, otherwise default to dummy layout guide
var compatibleSafeAreaLayoutGuide: UILayoutGuide {
if #available(iOS 11, *) {
return safeAreaLayoutGuide
} else {
if let layoutGuide = self.associatedLayoutGuide {
return layoutGuide
} else {
let layoutGuide = UILayoutGuide()
Constraint.on(
layoutGuide.topAnchor.constraint(equalTo: topAnchor),
layoutGuide.bottomAnchor.constraint(equalTo: bottomAnchor),
layoutGuide.leftAnchor.constraint(equalTo: leftAnchor),
layoutGuide.rightAnchor.constraint(equalTo: rightAnchor)
)

self.associatedLayoutGuide = layoutGuide

return layoutGuide
}
}
}

private struct AssociatedKeys {
static var layoutGuide = "layoutGuide"
}

fileprivate var associatedLayoutGuide: UILayoutGuide? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.layoutGuide) as? UILayoutGuide
}

set {
if let newValue = newValue {
objc_setAssociatedObject(
self, &AssociatedKeys.layoutGuide,
newValue as UILayoutGuide?,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
}

This way we can simply do

1
headerView.topAnchor.constraint(equalTo: view.compatibleSafeAreaLayoutGuide.topAnchor, constant: 20)

Read more

Comments