#if check(预处理器宏)来区分iPhone和iPad

Jus*_*ers 10 iphone objective-c c-preprocessor

是否有我可以检查的构建预处理器宏,用#if或#ifdef来确定我当前的Xcode项目是否是为iPhone或iPad构建的?

编辑

正如几个答案所指出的,通常应用程序是通用的,并且相同的二进制文件可以在两个设备上运行.这些非常相似的设备之间的条件行为应该在运行时而不是编译时解决.

Lou*_*nco 25

本博客评论部分的一些想法

http://greensopinion.blogspot.com/2010/04/from-iphone-to-ipad-creating-universal.html

主要使用

UI_USER_INTERFACE_IDIOM()
Run Code Online (Sandbox Code Playgroud)

如:

#ifdef UI_USER_INTERFACE_IDIOM()
  #define IS_IPAD() (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#else
  #define IS_IPAD() (false)
#endif
Run Code Online (Sandbox Code Playgroud)

  • 这实际上是在wwdc的苹果讲座中提出的. (2认同)

小智 9

NSString *deviceType = [UIDevice currentDevice].model;

if([deviceType isEqualToString:@"iPhone"]) {
    //iPhone
}
else if([deviceType isEqualToString:@"iPod touch"]) {
    //iPod Touch
}
else {
    //iPad
}
Run Code Online (Sandbox Code Playgroud)

就我而言,您不能使用#if或#ifdef来执行此操作,但是,它受支持,因为Obj-C是C的严格超集.

相关: 使用iPhone SDK确定设备(iPhone,iPod Touch)

  • 您不能对"通用二进制文件"进行编译时检查,因为它是为**构建的.如果您构建单独的iPad和iPhone应用程序,那么有很多方法,包括为不同的目标定义自己的编译器宏. (4认同)
  • 这不安全!明天Apple改变字符串,你的应用程序停止正常工作.来自UIDevice的userInterfaceIdiom属性是最安全的方式. (2认同)

Tri*_*ops 8

无法确定您的应用是否专为iPhone或iPad构建.#if在构建期间解析预处理器指令.一旦您的应用程序构建并标记为通用,它必须在两个设备上正确运行.在构建期间,没有人知道稍后将在何处安装,并且可以在两者上安装一个构建.

但是,您可能想要执行以下操作之一:

  1. 在运行时检测设备模型.

    要做到这一点,使用[[UIDevice currentDevice] model]和比较iPhone,iPod touchiPad字符串.即使在iPad 上以兼容模式运行(仅适用于iPhone的应用程序),这也会返回正确的设备.这对于使用情况分析非常有用.

  2. 在运行时检测用户界面习语.

    这是每个人在为iPhone和iPad提供不同内容时检查的内容.使用[[UIDevice currentDevice] userInterfaceIdiom]和比较UIUserInterfaceIdiomPhoneUIUserInterfaceIdiomPad.您可能想要制作这样的便利方法:

    @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
    
    Run Code Online (Sandbox Code Playgroud)

    然后你可以使用:

    if ([[UIDevice currentDevice] iPhone]) { }
    // or
    if ([UIDevice iPhone]) { }
    // or
    if (UIDevice.iPhone) { }
    
    Run Code Online (Sandbox Code Playgroud)

  • 为什么这不是接受的答案? (2认同)