如何检测我的设备是否为 Swift 4 中的 iPhone X?

How can I detect if my device is an iPhoneX in Swift 4?

我相信有更好、更合适的方法来做到这一点。但是现在我正在使用 UIScreen.main.bounds 来检测我是否正在处理 iPhone X(812 高)。顺便说一句,这个特定的应用程序仅限横向。这就是我在这个函数中所拥有的,我正在为幻灯片视图制作幻灯片:

func setupSlideViews(slideView: [SlideView]) {
    let screenSize = UIScreen.main.bounds

    var frame: CGRect!
    if screenSize.width == 812 {
        frame = scrollView.frame
    } else {
        frame = view.frame
    }
    scrollView.frame = frame
    scrollView.contentSize = CGSize(width: frame.width * CGFloat(slideViews.count), height: frame.height)

    for (i, slideView) in slideViews.enumerated() {
        slideView.frame = CGRect(x: frame.width * CGFloat(i), y: 0, width: frame.width, height: frame.height)
        scrollView.addSubview(slideView)
    }
}

但是您如何检查模型?

如果您需要检测设备是否为 iPhoneX,请不要使用 bounds,这取决于设备的方向。因此,如果用户以纵向模式打开您的应用程序,它将失败。您可以使用设备 属性 nativeBounds,它在旋转时不会改变。

In iOS 8 and later, a screen’s bounds property takes the interface orientation of the screen into account. This behavior means that the bounds for a device in a portrait orientation may not be the same as the bounds for the device in a landscape orientation. Apps that rely on the screen dimensions can use the object in the fixedCoordinateSpace property as a fixed point of reference for any calculations they must make. (Prior to iOS 8, a screen’s bounds rectangle always reflected the screen dimensions relative to a portrait-up orientation. Rotating the device to a landscape or upside-down orientation did not change the bounds.)

extension UIDevice {
    var iPhoneX: Bool {
        return UIScreen.main.nativeBounds.height == 2436
    }
}

用法

if UIDevice.current.iPhoneX { 
    print("This device is a iPhoneX")
}