在iOS编程时,经常会遇到UI适配,在不同的机型或者iPhone、iPad的UI适配,下面就介绍如何区分iPhone和iPad等设备。
- UI_USER_INTERFACE_IDIOM()
- UIUserInterfaceIdiom
UI_USER_INTERFACE_IDIOM() 是一个内联函数,它是用来获取设备的UI类型,比如 iPhone 的UI类型,该内联函数实现细节如下
static inline UIUserInterfaceIdiom UI_USER_INTERFACE_IDIOM() {
return ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ?
[[UIDevice currentDevice] userInterfaceIdiom] :
UIUserInterfaceIdiomPhone);
}
由此可以看出 UI_USER_INTERFACE_IDIOM() 函数返回值就是一个 UIUserInterfaceIdiom 类型的枚举值
UIUserInterfaceIdiom 设备UI类型枚举
typedef NS_ENUM(NSInteger, UIUserInterfaceIdiom) {
UIUserInterfaceIdiomUnspecified = -1,
UIUserInterfaceIdiomPhone NS_ENUM_AVAILABLE_IOS(3_2), // iPhone and iPod touch style UI
UIUserInterfaceIdiomPad NS_ENUM_AVAILABLE_IOS(3_2), // iPad style UI
UIUserInterfaceIdiomTV NS_ENUM_AVAILABLE_IOS(9_0), // Apple TV style UI
UIUserInterfaceIdiomCarPlay NS_ENUM_AVAILABLE_IOS(9_0), // CarPlay style UI
};
具体用法,很简单
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// 做 iPad 的 UI 适配
} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
// 做 iPhone 的 UI 适配
}
以此类推啦,很简单的。
网友评论