是否有构建预处理宏可以使用#if
或#ifdef
检查,以确定我的当前Xcode项目正在构建的是iPhone还是iPad?
编辑
正如几个答案所指出的那样,通常应用程序是通用的,同一二进制文件可以在两个设备上运行。这些非常相似的设备之间的条件行为应该在运行时而不是编译时解决。
是否有构建预处理宏可以使用#if
或#ifdef
检查,以确定我的当前Xcode项目正在构建的是iPhone还是iPad?
编辑
正如几个答案所指出的那样,通常应用程序是通用的,同一二进制文件可以在两个设备上运行。这些非常相似的设备之间的条件行为应该在运行时而不是编译时解决。
这篇博客的评论部分提出了一些想法。
http://greensopinion.blogspot.com/2010/04/from-iphone-to-ipad-creating-universal.html
主要使用:
UI_USER_INTERFACE_IDIOM()
例如:
#ifdef UI_USER_INTERFACE_IDIOM()
#define IS_IPAD() (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#else
#define IS_IPAD() (false)
#endif
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:@"iPhone"]) {
//iPhone
}
else if([deviceType isEqualToString:@"iPod touch"]) {
//iPod Touch
}
else {
//iPad
}
无法确定您的应用程序是为iPhone还是iPad构建的。预处理器#if
指令在构建期间解析。一旦您的应用程序被构建并标记为通用,它必须在两个设备上正确运行。在构建过程中,没有人知道它将被安装在哪里,一个构建版本可以安装在两个设备上。
但是您可能想要执行以下操作之一:
Detect device model during runtime.
To do this, use [[UIDevice currentDevice] model]
and compare to iPhone
, iPod touch
or iPad
strings. This will return you correct device even when running in compatibility mode on iPad (for iPhone-only apps). This can be usefull for usage analytics.
Detect user interface idiom during runtime.
This is what everyone checks for, when providing different content for iPhone and iPad. Use [[UIDevice currentDevice] userInterfaceIdiom]
and compare to UIUserInterfaceIdiomPhone
or UIUserInterfaceIdiomPad
. You may want to make convenience methods like this:
@implementation UIDevice (UserInterfaceIdiom)
- (BOOL)iPhone {
return (self.userInterfaceIdiom == UIUserInterfaceIdiomPhone);
}
+ (BOOL)iPhone {
return [[UIDevice currentDevice] iPhone];
}
- (BOOL)iPad {
return (self.userInterfaceIdiom == UIUserInterfaceIdiomPad);
}
+ (BOOL)iPad {
return [[UIDevice currentDevice] iPad];
}
@end
Then you can use:
if ([[UIDevice currentDevice] iPhone]) { }
// or
if ([UIDevice iPhone]) { }
// or
if (UIDevice.iPhone) { }
Swift 更新:
无法使用预处理器。将全局函数设为
func IS_IPAD() -> Bool {
( return (UIDevice.respondsToSelector(Selector("userInterfaceIdiom"))) && (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad) )}
我在AppleTV 4上使用以下代码,因为UIUserInterfaceIdiomUnspecified似乎不起作用,也找不到其他枚举值:
#ifdef TARGET_OS_IOS
CGSize result = [[UIScreen mainScreen] bounds].size;
if(result.width == 1920) {
NSLog(@"tvOS");
}
#endif
在黑暗时代之前,我曾经在iPad等设备上使用过这个技巧-OB1,哈哈晚安。但是你可以将这种类似的技术用于其他屏幕尺寸。
UI_USER_INTERFACE_IDIOM
的优势是不存在的。 - Tricertops