以编程方式检测 iPad/iPhone 硬件的最佳方法 [英] Best way to programmatically detect iPad/iPhone hardware
问题描述
我需要找出的原因是在 iPad 上, UIPickerView 在横向和纵向具有相同的高度.在 iPhone 上则不同.iPad 编程指南向 UIDevice 引入了一个惯用语"值:
The reason I need to find out is that on an iPad, a UIPickerView has the same height in landscape orientation as it does in portrait. On an iPhone it is different. The iPad programming guide introduces an "idiom" value to UIDevice:
UIDevice* thisDevice = [UIDevice currentDevice];
if(thisDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad)
{
// iPad
}
else
{
// iPhone
}
当您使用 iPad (3.2) 而不是 iPhone (3.1.3) 时它可以正常工作 - 所以看起来还需要一个 ifdef 来有条件地编译该检查,例如:
which works OK while you're in iPad (3.2) but not iPhone (3.1.3) - so it looks like there also needs to be an ifdef to conditionally compile that check, like:
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 30200
UIDevice* thisDevice = [UIDevice currentDevice];
if(thisDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad)
{
// etc.
}
#endif
对我来说,这开始看起来很笨拙.什么是更好的方法?
To me that's starting to look very clumsy. What's a better way?
推荐答案
我现在(并且在这个较晚的日期)回答这个问题,因为许多现有的答案已经很旧了,而且投票最多的实际上似乎是错误的根据 Apples 当前文档(iOS 8.1, 2015)!
I'm answering this now (and at this late date) because many of the existing answers are quite old, and the most Up Voted actually appears to be wrong according to Apples current docs (iOS 8.1, 2015)!
为了证明我的观点,这是来自 Apples 头文件的注释(总是查看 Apple 源代码和头文件):
To prove my point, this is the comment from Apples header file (always look at the Apple source and headers):
/*The UI_USER_INTERFACE_IDIOM() macro is provided for use when
deploying to a version of the iOS less than 3.2. If the earliest
version of iPhone/iOS that you will be deploying for is 3.2 or
greater, you may use -[UIDevice userInterfaceIdiom] directly.*/
因此,目前APPLE推荐检测iPhone vs. iPad的方式如下:
Therefore, the currently APPLE recommended way to detect iPhone vs. iPad, is as follows:
1) (自 iOS 13 起弃用) 在 iOS PRIOR 到 3.2 的版本上,使用 Apple 提供的宏:
1) (DEPRECATED as of iOS 13) On versions of iOS PRIOR to 3.2, use the Apple provided macro:
// for iPhone use UIUserInterfaceIdiomPhone
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
2) 在 iOS 3.2 或更高版本上,使用 [UIDevice currentDevice] 上的属性:
2) On versions of iOS 3.2 or later, use the property on [UIDevice currentDevice]:
// for iPhone use UIUserInterfaceIdiomPhone
if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad)
这篇关于以编程方式检测 iPad/iPhone 硬件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!