简体   繁体   English

iOS11设备上safeAreaInset的不同返回没有缺口

[英]Different return of safeAreaInset on iOS11 device without notch

Currently I am using the following snippet to get the safeAreaInset.top value to set up a constraint for my view.目前我正在使用以下代码段来获取 safeAreaInset.top 值来为我的视图设置约束。

extension UIDevice {
     var safeAreaInsets: UIEdgeInsets {
         if #available(iOS 11.0, *) {
             if let keyWindow = UIApplication.shared.windows.filter({ $0.isKeyWindow}).first {
                 return keyWindow.safeAreaInsets
             }
         }
         return UIEdgeInsets.zero
     }
}

On iPhone with iOS 12 or above, the safeAreaInsets seems doing fine, returning UIEdgeInsets(20, 0, 0, 0) for device without notch and UIEdgeInsets(47, 0, 34, 0) for device with notch.在具有 iOS 12 或更高版本的 iPhone 上,safeAreaInsets 似乎做得很好,为没有缺口的设备返回UIEdgeInsets(20, 0, 0, 0)为有缺口的设备UIEdgeInsets(47, 0, 34, 0)

But on iOS 11, the safeAreaInset always return UIEdgeInsets(0, 0, 0, 0) for device without notch.但是在 iOS 11 上,safeAreaInset 始终为没有缺口的设备返回UIEdgeInsets(0, 0, 0, 0)

I tried it on different size devices without notch (iPhone7, iPhone8, iPhone8 Plus), and they only return UIEdgeInset(0, 0, 0, 0) on iOS 11 version (11.2, 11.4, etc), but returning the correct UIEdgeInset(20, 0, 0, 0) on other iOS 11+ version.我在没有缺口的不同尺寸设备(iPhone7、iPhone8、iPhone8 Plus)上尝试过,它们只在 iOS 11 版本(11.2、11.4 等)上返回UIEdgeInset(0, 0, 0, 0) ,但返回正确的UIEdgeInset(20, 0, 0, 0)在其他 iOS 11+ 版本上。 (And on devices with notch, seems they return the correct safeAreaInset UIEdgeInset(47, 0, 34, 0) for all iOS 11 or above version.) (在带有缺口的设备上,它们似乎为所有 iOS 11 或更高版本返回了正确的 safeAreaInset UIEdgeInset(47, 0, 34, 0) 。)

My question is, why safeAreaInset return differently only on iOS 11 device without notch, and what is the appropriate way to get the safeAreaInset.我的问题是,为什么 safeAreaInset 仅在没有缺口的 iOS 11 设备上返回不同,以及获取 safeAreaInset 的适当方法是什么。

Declare window in your AppDelegate first like this:首先在您的 AppDelegate 中声明 window,如下所示:

var window: UIWindow?

You can get the safeAreaInsets like this:您可以像这样获得 safeAreaInsets:

let _appDelegator = { return UIApplication.shared.delegate! as! AppDelegate }()

var _safeAreaInsets: UIEdgeInsets {
    get {
        if let window = _appDelegator.window{
            return window.safeAreaInsets
        }else if let vc = _appDelegator.window?.rootViewController{
            return vc.view.safeAreaInsets
        }
        return UIEdgeInsets.zero
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM