#if check (preprocessor macro) to differentiate between iPhone and iPad

后端 未结 5 1152
别那么骄傲
别那么骄傲 2021-02-04 12:13

Is there a build preprocessor macro I can check, with #if or #ifdef to determine if my current Xcode project is being built for iPhone or iPad?

5条回答
  •  你的背包
    2021-02-04 13:15

    There is no way to determine whether your app is built for iPhone or iPad. Preprocessor #if directives are resolved during build. Once your app is built and flagged as Universal, it has to run correctly on both devices. During building nobody knows where it will be installed later and one build can be installed on both.

    However you may want to do one of these:

    1. 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.

    2. 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) { }
      

提交回复
热议问题