I'm adapting an app to support iPhone X. I have a share extension with a custom view controller. I need to know the safe area insets of my device, but the safeAreaInsets
method from UIWindow
provided by calling UIApplication.shared.keyWindow
isn't available in the Share Extension because UIApplication.shared
is not visible there.
Is there a way to know the values from the safeAreaInsets
property in my Share Extension?
Asked
Active
Viewed 1,010 times
10

Nicola Giancecchi
- 3,045
- 2
- 25
- 41
1 Answers
7
safeAreaInsets
is a property on any UIView; you can use that in your Share Extension. You don't need to ask UIApplication.shared.keyWindow
for safeAreaInsets - in fact, you probably don't want to do that, because if the keyWindow contains a UINavigationController
or a UITabBarController
, those would affect the safeAreaInsets.
If you have a view deep in your UIView
hierarchy, its safeAreaInsets
are calculated by looking at ancestor views in the hierarchy, and seeing if any of them have safeAreaInsets
that overlap with your view.
You may find, however, that the safeAreaInsets
are initially UIEdgeInsets.zero
- what you'll want to do is implement UIView.safeAreaInsetsDidChange()
or UIViewController.viewSafeAreaInsetsDidChange()
, like so:
public override func safeAreaInsetsDidChange() {
if #available(iOS 11.0, *) {
super.safeAreaInsetsDidChange()
self.setNeedsUpdateConstraints() // or self.setNeedsLayout, etc.
}
}

bryanjclark
- 6,247
- 2
- 35
- 68