아이폰 X, XS, XS MAX, XR 대응 코드

2018. 10. 11. 11:23아이폰 개발

https://stackoverflow.com/questions/46192280/detect-if-the-device-is-iphone-x


You shall perform different detections of iPhone X depending on the actual need.

for dealing with the top notch (statusbar, navbar), etc.

class var hasTopNotch: Bool {
    if #available(iOS 11.0, tvOS 11.0, *) {
        // with notch: 44.0 on iPhone X, XS, XS Max, XR.
        // without notch: 20.0 on iPhone 8 on iOS 12+.
        return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 20
    }
    return false
}

for dealing with the bottom home indicator (tabbar), etc.

class var hasBottomSafeAreaInsets: Bool {
    if #available(iOS 11.0, tvOS 11.0, *) {
        // with home indicator: 34.0 on iPhone X, XS, XS Max, XR.
        return UIApplication.shared.delegate?.window??.safeAreaInsets.bottom ?? 0 > 0
    }
    return false
}

for backgrounds size, fullscreen features, etc.

class var isIphoneXOrBigger: Bool {
    // 812.0 on iPhone X, XS.
    // 896.0 on iPhone XS Max, XR.
    return UIScreen.main.bounds.height >= 812
}

Note: eventually mix it with UIDevice.current.userInterfaceIdiom == .phone
Note: this method requires to have a LaunchScreen storyboard or proper LaunchImages

for backgrounds ratio, scrolling features, etc.

class var isIphoneXOrLonger: Bool {
    // 812.0 / 375.0 on iPhone X, XS.
    // 896.0 / 414.0 on iPhone XS Max, XR.
    return UIScreen.main.bounds.height / UIScreen.main.bounds.width >= 896.0 / 414.0
}

Note: this method requires to have a LaunchScreen storyboard or proper LaunchImages