可以将if语句放到#define中吗?

时间:2012-02-22 05:57:39

标签: iphone objective-c ios xcode

我正在尝试修改现有的库,以便与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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;
}

答案 2 :(得分:0)

你可以这样做,

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

答案 3 :(得分:-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;
}