1

我想根据不同的设备高度动态定义一个常数。我尝试使用此代码,但它不起作用:

#define isPhone568 ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height == 568)

#ifdef isPhone568
    #define kColumnHeightPortrait568 548
#else
    #define kColumnHeightPortrait568 (IS_IPAD ? 984 : 460)
#endif

即使我使用的是 3.5" 模拟器,我也会得到 548。这有什么问题?

4

2 回答 2

2

您不能在宏定义中运行代码,这是一个在编译时发生的简单文本替换过程。因此,您当时不知道设备特征是什么,因为您不在目标设备上。

如果你想使用类似的东西[UIDevice currentDevice] userInterfaceIdiom,你必须在运行时评估它,而不是在编译时宏中,比如:

int kColumnHeightPortrait568 = 548;
if (([[UIDevice currentDevice] userInterfaceIdiom] != UIUserInterfaceIdiomPhone)
   || ([UIScreen mainScreen].bounds.size.height != 568))
{
    kColumnHeightPortrait568 = (IS_IPAD ? 984 : 460);
}
于 2012-09-21T09:10:55.573 回答
1

#ifdef用于检查是否定义了宏。正如您isPhone568在第一行中定义的那样,#ifdef isPhone568将是正确的。

如果要测试表达式的值而不是宏的存在,则应#if改为使用。但#if只能测试简单的算术表达式,正如paxdiablo所说,“你不能在宏定义中运行代码”。

于 2012-09-21T09:40:39.167 回答