关于ios:如何检测我的设备是否是Swift 4中的iPhoneX?

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

本问题已经有最佳答案,请猛点这里访问。

我确信有一种更好、更合适的方法可以做到这一点。但现在我正在使用uiscreen.main.bounds来检测我是否在处理iPhoneX(812高)。这个特定的应用程序只是横向的,顺便说一句。所以这就是我在这个功能中所拥有的,在这个功能中,我为一个幻灯片视图装箱幻灯片:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.)

1
2
3
4
5
extension UIDevice {
    var iPhoneX: Bool {
        return UIScreen.main.nativeBounds.height == 2436
    }
}

使用

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