Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect safe area insets on Share Extension

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?

like image 349
Nicola Giancecchi Avatar asked Oct 11 '17 09:10

Nicola Giancecchi


1 Answers

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.
    }
}
like image 81
bryanjclark Avatar answered Oct 02 '22 21:10

bryanjclark