在 Swift 中 使用 UI_USER_INTERFACE_IDIOM() 查看当前设备

在 Swift 中与 UI_USER_INTERFACE_IDIOM() 等同的、用于检测设备是 iPhone 还是 iPad 的方法是什么呢?


Swift 中可以使用 enum UIUserInterfaceIdiom,定义如下:

enum UIUserInterfaceIdiom : Int {
    case unspecified

    case phone // iPhone 和 iPod touch 形式的 UI
    case pad // iPad 形式的 UI
}

所以可以这么使用:

UIDevice.current.userInterfaceIdiom == .pad
UIDevice.current.userInterfaceIdiom == .phone
UIDevice.current.userInterfaceIdiom == .unspecified

或者用 Switch 语句:

switch UIDevice.current.userInterfaceIdiom {
    case .phone:
        // 这是 iPhone
    case .pad:
        // 这是 iPad
    case .unspecified:
        // Uh, oh! 这什么鬼?
    }

UI_USER_INTERFACE_IDIOM() 是一个 Objective-C 宏指令,定义为:

#define UI_USER_INTERFACE_IDIOM() \ ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? \ [[UIDevice currentDevice] userInterfaceIdiom] : \ UIUserInterfaceIdiomPhone)

还有,注意在编写 Objective-C 时,UI_USER_INTERFACE_IDIOM() 宏只在 iOS 3.2 或以下需要用到。开发 iOS 3.2 或以上的版本时,直接用 [UIDevice userInterfaceIdiom] 就好了。

你可能感兴趣的:(在 Swift 中 使用 UI_USER_INTERFACE_IDIOM() 查看当前设备)