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

前端 未结 9 844
情话喂你
情话喂你 2021-02-05 04:07

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.

相关标签:
9条回答
  • 2021-02-05 04:47

    Swift 5

    var hasNotch: Bool {
        if #available(iOS 11.0, tvOS 11.0, *) {
            let bottom = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0
            return bottom > 0
        } else {
            return false
        }
    }
    
    0 讨论(0)
  • 2021-02-05 04:50

    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
    }
    
    0 讨论(0)
  • 2021-02-05 04:51

    Swift 5, iOS 14 supported

    Thanks to @Tanin and @DominicMDev, since keyWindow was deprecated in iOS 13 and the iPad Pro has non-zero safeAreaInsets, this works fine for me.

    (Already tested on iPhone 8, iPhone 11 Pro and iPad Pro (11-inch)(2nd gen) Simulators)

    extension UIDevice {
        /// Returns `true` if the device has a notch
        var hasNotch: Bool {
            guard #available(iOS 11.0, *), let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first else { return false }
            if UIDevice.current.orientation.isPortrait {
                return window.safeAreaInsets.top >= 44
            } else {
                return window.safeAreaInsets.left > 0 || window.safeAreaInsets.right > 0
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题