2012-02-22 68 views
3

我正在嘗試修改現有庫以與iPhone和iPad一起使用。有一對夫婦的語句我想修改:可能把語句放到#define中嗎?

#define width 320 
#define height 50 

我想這樣做:

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

但是我似乎無法做到這一點。有沒有辦法實現這樣的事情?由於

回答

-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; 
} 
+0

可能想使用'static const's而不是'#define's。 – 2012-02-22 06:03:44

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; 
} 
+0

請說明降低投票的理由。 – 2012-02-22 06:38:31

+1

+1,因爲在這種情況下,真的建議在運行時定義寬度/高度。您可能收到-1,因爲您沒有真正回答原始問題:如何在#define中使用'if'。無論如何:如果他正在編譯兩個不同的目標(一個用於iPad的iPhone)而不是一個(通用的),那麼在編譯時使用#if來定義這個屬性沒有任何錯誤。 – 2012-02-22 08:32:10

0

你能做到這樣,

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

如果您在應用程序周圍使用了一百次寬度和高度,編譯器將在整個地方粘貼這個難看的代碼。你應該儘可能避免使用宏。 – 2012-02-22 06:08:26

+0

@arasmussen,謝謝你的建議。將牢記在心。 – Vignesh 2012-02-22 06:15:53

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; 
}