Define a constant based on device type

I have a file called Constants.h that actually contains some global constants. Since my application was created for both iPhone and iPad, I would like to define the same constants (i.e. with the same name) differently for the two types of devices.

For a full explanation:

/******** pseudo code *********/ if (deviceIsIPad){ #define kPageMargin 20 } else { #define kPageMargin 10 } 

How can i do this? Thanks.

l

+6
source share
5 answers

Unable to get device type during preprocessing step. It is determined dynamically at runtime. You have two options:

  • Create two different targets (for iPhone and iPad, respectively) and define a macro there.

  • Create a macro that inserts an expression as follows:

  #define IS_IPAD (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) #define kMyConstant1 (IS_IPAD ? 100 : 200) #define kMyConstant2 (IS_IPAD ? 210 : 230) #define kMyConstant3 (IS_IPAD ? @"ADASD" : @"XCBX") 
+18
source

#define resolves at compile time, i.e. on your computer

Obviously, you cannot make them conditional as you want. I recommend creating a static variable and setting them in the +(void)initialise method of your class.

And for the condition, use something like

 if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // iPad } else { // iPhone or iPod touch. } 

So it will be

 static NSInteger foo; @implementation bar +(void)initialise{ if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // iPad foo = 42; } else { // iPhone or iPod touch. foo = 1337; } } @end 
+2
source

Hi, write this code in the appdelegate class

  +(NSString *)isAppRunningOnIpad:(NSString *)strNib{ NSString *strTemp; NSString *deviceType = [UIDevice currentDevice].model; if ([deviceType hasPrefix:@"iPad"]){ strTemp=[NSString stringWithFormat:@"%@I",strNib]; } else{ strTemp=strNib; } return strTemp; } 

call it from your class using this line

 SecondVC *obj_secondvc = [[SecondVC alloc] initWithNibName:[AppDelegate isAppRunningOnIpad:@"SecondVC"] bundle:nil]; 
0
source

Use UIDevice macros - http://d3signerd.com/tag/uidevice/

Then you can write code, for example:

 if ([DEVICE_TYPE isEqualToString:DEVICE_IPAD]) { } 

or

 if (IS_SIMULATOR && IS_RETINA) { } 
0
source

You cannot do this with definitions, because they expand at compile time. However, you can define the variables and set their initial value based on the user interface idiom:

 // SomeClass.h extern CGFloat deviceDependentSize; // SomeClass.m - (id)init { // ... if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad]) deviceDependentSize = 1024.0f; // iPad else deviceDependentSize = 480.0f; // iPhone // etc. } 
0
source

Source: https://habr.com/ru/post/922346/


All Articles