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

标签 ios swift iphone-x

<分区>

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

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")
}

关于ios - 如何检测我的设备是否是 Swift 4 中的 iPhone X?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46633487/

相关文章:

ios - iPhone X 的 UIView 高度没有扩展

ios - Xcode Storyboard 使按钮高度等于底部布局指南(或安全区域下方的空间)+ 常数?

ios - Iphone X 屏幕未覆盖 cordova 项目中的页眉和页脚

ios - UIViewController presentViewController :animated:completion - taking 4 to 6 seconds to launch

ios - Swift - 减少 UICollectionViewCell 之间的间隙

ios - swift3 scrollToRow 即使有空单元格

ios - Storyboard:删除派生数据中的文件夹后仍然是 "Unable to write to path"

ios - 为什么我收到错误 : fatal error: unexpectedly found nil while unwrapping an Optional value?

ios - 如何在适用于 IOS 的 xamarin.forms 应用程序中设置应用程序的应用程序图标

ios - iOS 的 Github API