iOS: Detect if the device is iPhone X family (frameless)

这一生的挚爱 提交于 2020-01-01 04:44:05

问题


In my app there is some logic for frameless devices (iPhoneX, Xs Xs max, Xr). Currently it works base on the model of the devices, so, I detect the model by DeviceKit framework.

But I want to extend this logic to future frameless devices. Probably in one year we will have some extra frameless devices. So, how can I detect if device is frameless or not? It should cover all current frameless devices and future one.

We can not rely on faceID, safeAreaInset, screen height or size. So, then what?


回答1:


You could "fitler" for the top notch, something like:

var hasTopNotch: Bool {
    if #available(iOS 11.0, tvOS 11.0, *) {
        return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 20
    }
    return false
}



回答2:


This way you can cover all the orientations:

var hasTopNotch: Bool 
{
    if #available(iOS 11.0,  *) {

        var safeAreaInset: CGFloat?
        if (UIApplication.shared.statusBarOrientation == .portrait) {
            safeAreaInset = UIApplication.shared.delegate?.window??.safeAreaInsets.top
        }
        else if (UIApplication.shared.statusBarOrientation == .landscapeLeft) {
            safeAreaInset = UIApplication.shared.delegate?.window??.safeAreaInsets.left
        }
        else if (UIApplication.shared.statusBarOrientation == .landscapeRight) {
            safeAreaInset = UIApplication.shared.delegate?.window??.safeAreaInsets.right
        }
        return safeAreaInset ?? 0 > 24
    }
    return false
}



回答3:


This is valid for any orientation. No need to worry about iOS version before 11.0 since iPhone X minimum version is 11.0. Source

extension UIDevice {

    var hasNotch: Bool {
        if #available(iOS 11.0, *) {
           return UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0 > 0
        }
        return false
   }
}



回答4:


I am doing it like this because the iPadPro has non-zero safeAreaInsets.

extension UIDevice {

    /// Returns 'true' if the device has a notch
    var hasNotch: Bool {
        guard #available(iOS 11.0, *), let window = UIApplication.shared.keyWindow else { return false }
        let orientation = UIApplication.shared.statusBarOrientation
        if orientation.isPortrait {
            return window.safeAreaInsets.top >= 44
        } else {
            return window.safeAreaInsets.left > 0 || window.safeAreaInsets.right > 0
        }
    }

}


来源:https://stackoverflow.com/questions/52402477/ios-detect-if-the-device-is-iphone-x-family-frameless

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!