可以在#define中放置if语句吗?

3

我正在尝试修改一个现有的库,使其适用于iPhone和iPad。我想要修改几个语句:

#define width 320
#define height 50

我希望能够做类似于以下操作的事情:

代码示例:

if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
  #define width X
  #define height Y }
else {
  #define width A
  #define height B
}

然而,似乎我不能这样做。有没有一种方法可以实现这样的功能?谢谢。
4个回答

2
你可以使用#if
 #if TARGET_DEVICE_IPHONE // note this may be different, don't have acces to Xcode right now.
 #define width X
 #define height Y
 #else
 #define width A
 #define height B
 #endif

或者只需创建一个简单的内联函数:
static inline int width()
{
      return [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ? X : A;
}

static inline int height()
{
    return [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ? Y : B;
}

0

#define 是一个预处理器定义。这意味着这是编译中执行的第一件事情。它基本上只是在编译之前将定义粘贴到代码的各个位置。

但由于您的 if 语句是在运行时而不是编译时执行的,因此您需要将 if 语句更改为预处理器 if(#if,不建议使用),或者更改您的宽度/高度以在运行时定义(强烈建议)。这应该像这样:

int width, height;
if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
  width = X;
  height = Y;
else {
  width = A;
  height = B;
}

然后从那时起,只需使用宽度和高度值作为您的宽度和高度。

如果您仍想标记X、Y、A、B,而不是使用#define(编译时常量),请使用运行时常量:

static const int iPhoneWidth = X;
static const int iPhoneHeight = Y;
static const int iPadWidth = A;
static const int iPadHeight = B;

if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
  width = iPhoneWidth;
  height = iPhoneHeight;
else {
  width = iPadWidth;
  height = iPadHeight;
}

请说明下投票反对的原因。 - Andrew Rasmussen
1
+1 因为在这种情况下,强烈建议在运行时定义宽度/高度。你可能收到-1是因为你没有真正回答原始问题:如何在#define中使用'if'。无论如何:如果他正在编译两个不同的目标(一个用于iPhone,一个用于iPad),而不是一个(通用)目标,那么在编译时使用#if来定义这些属性是没有问题的。 - Rok Jarc

0

你可以这样做,

#define width (([[UIDevice currentDevice] userInterfaceIdiom] != UIUserInterfaceIdiomPhone) ? A : x)
#define height (([[UIDevice currentDevice] userInterfaceIdiom] != UIUserInterfaceIdiomPhone) ? B : Y)

1
如果你在应用程序中使用宽度和高度一百次,编译器会在各处粘贴这段丑陋的代码。如果可能的话,你真的应该避免使用宏。 - Andrew Rasmussen

-1

这样怎么样:

#define widthPhone 320
#define widthPad 400
#define heightPhone 50
#define heightPad 90

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    width = widthPhone;
    height = heightPhone;
} else {
    width = widthPad;
    height = heightPad;
}

可能需要使用static const而不是#define - Andrew Rasmussen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接