在 Swift 中使用 UI_USER_INTERFACE_IDIOM() 检测当前设备 [英] Detect current device with UI_USER_INTERFACE_IDIOM() in Swift
问题描述
Swift 中 UI_USER_INTERFACE_IDIOM()
在 iPhone 和 iPad 之间检测的等价物是什么?
What is the equivalent of UI_USER_INTERFACE_IDIOM()
in Swift to detect between iPhone and iPad?
在 Swift 中编译时出现 Use of unresolved identifier
错误.
I get an Use of unresolved identifier
error when compiling in Swift.
推荐答案
使用 Swift 时,可以使用 enum
UIUserInterfaceIdiom
,定义为:
When working with Swift, you can use the enum
UIUserInterfaceIdiom
, defined as:
enum UIUserInterfaceIdiom : Int {
case unspecified
case phone // iPhone and iPod touch style UI
case pad // iPad style UI (also includes macOS Catalyst)
}
因此您可以将其用作:
UIDevice.current.userInterfaceIdiom == .pad
UIDevice.current.userInterfaceIdiom == .phone
UIDevice.current.userInterfaceIdiom == .unspecified
或者使用 Switch 语句:
Or with a Switch statement:
switch UIDevice.current.userInterfaceIdiom {
case .phone:
// It's an iPhone
case .pad:
// It's an iPad (or macOS Catalyst)
@unknown default:
// Uh, oh! What could it be?
}
UI_USER_INTERFACE_IDIOM()
是一个 Objective-C 宏,定义为:
UI_USER_INTERFACE_IDIOM()
is an Objective-C macro, which is defined as:
#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]
.
Also, note that even when working with Objective-C, the UI_USER_INTERFACE_IDIOM()
macro is only required when targeting iOS 3.2 and below. When deploying to iOS 3.2 and up, you can use [UIDevice userInterfaceIdiom]
directly.
这篇关于在 Swift 中使用 UI_USER_INTERFACE_IDIOM() 检测当前设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!