使用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中编译时出现使用未解析的标识符
错误。
I get an Use of unresolved identifier
error when compiling in Swift.
推荐答案
使用Swift,您可以使用枚举
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
}
因此您可以将其用作:
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
case .unspecified:
// 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,仅在定位iOS 3.2及更低版本时才需要 UI_USER_INTERFACE_IDIOM()
宏。部署到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屋!