Iphone 根据设备类型定义常量

Iphone 根据设备类型定义常量,iphone,objective-c,constants,device,definition,Iphone,Objective C,Constants,Device,Definition,我有一个Constants.h文件,它实际上包含一些全局常量。因为我的应用程序是为iPhone和iPad构建的,所以我想为这两种设备类型定义不同的常量(即同名) 有关完整的解释: /******** pseudo code *********/ if (deviceIsIPad){ #define kPageMargin 20 } else { #define kPageMargin 10 } 我该怎么做? 谢谢 L.在appdelegate类中编写此代码 +(NSS

我有一个Constants.h文件,它实际上包含一些全局常量。因为我的应用程序是为iPhone和iPad构建的,所以我想为这两种设备类型定义不同的常量(即同名)

有关完整的解释:

/******** pseudo code *********/

if (deviceIsIPad){
    #define kPageMargin 20
}
else {
    #define kPageMargin 10
}
我该怎么做? 谢谢


L.

appdelegate
类中编写此代码

    +(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;
}
用这条线从你的班上打电话

SecondVC *obj_secondvc = [[SecondVC alloc] initWithNibName:[AppDelegate isAppRunningOnIpad:@"SecondVC"] bundle:nil]; 
#define
在编译时解析(即在计算机上)

显然,你不能让他们有你想要的条件。我建议创建
static
变量,并在类的
+(void)initialise
方法上设置它们

对于这种情况,使用类似

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {   
    // iPad 
} else {   
    // iPhone or iPod touch. 
}
这样就可以了

static NSInteger foo;

@implementation bar

+(void)initialise{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {   
        // iPad 
        foo = 42;
    } else {   
        // iPhone or iPod touch. 
        foo = 1337;
    }
}

@end

在预处理步骤中不可能获取设备类型。它是在运行时动态确定的。您有两个选择:

  • 创建两个不同的目标(分别针对iPhone和iPad)并在其中定义宏

  • 创建插入表达式的宏,如下所示:

  • 使用UIDevice宏-

    然后您可以编写如下代码:

    if ([DEVICE_TYPE isEqualToString:DEVICE_IPAD]) {
    
    }
    


    您不能使用定义来实现这一点,因为它们是在编译时展开的。但是,您可以根据用户界面习惯用法定义变量并设置其初始值:

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

    这不是一个类,它是一个头文件,因此它从来没有初始化过一个我无法从那里调用的方法..在你的AppDelegate类上使用它,这样它在整个AppDelegate类中都可以访问。我想我会尝试第二个选项,如果它工作正常,我会将你的答案标记为正确:)太棒了,你为我节省了这么多时间!
    if (IS_SIMULATOR && IS_RETINA) {
    
    }
    
    // SomeClass.h
    extern CGFloat deviceDependentSize;
    
    // SomeClass.m
    - (id)init
    {
        // ...
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad])
            deviceDependentSize = 1024.0f; // iPad
        else
            deviceDependentSize = 480.0f; // iPhone
    
    
        // etc.
    }