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?
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With