7

I'm trying to make my iPhone app compatible with the iPad. In a header file I set up some constants. Because of the larger screen I want some constants used for images to be larger on the iPad than on to the iPhone. I found some suggestions on the internet to accomplish this:

#if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define imgAmcWidth 656.0f
#define imgAmcHeight 36.0f
#else
#define imgAmcWidth    240.0f
#define imgAmcHeight   20.0f
#endif

This seems to satisfy my needs. Unfortunately xcode 4 fails to compile this giving an error: 'Token "[" is not valid in preprocessor..' [LLVM GCC 4.2]. What am I doing wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ghislain
  • 289
  • 2
  • 6

2 Answers2

21

While probably not the most elegant solution but to prevent a major rewrite of the code I decided to use the following trick:

#define iPad    UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
#define imgAmcWidth         (iPad ? 639.0f : 240.0f)
// etc..
Ghislain
  • 289
  • 2
  • 6
  • 2
    You should put parentheses around your macro definition, or you may wind up with weird precedence or operand mismatch errors. The parentheses make your macros "safe" to use in more contexts. – Dalbergia Nov 07 '11 at 16:23
  • If this method is used for constants that are referenced a lot, it will slow down the app a ton. – Letrstotheprez Dec 09 '12 at 22:39
5

UI_USER_INTERFACE_IDIOM and UIUserInterfaceIdiomPad are not preprocessor things. They are part of iOS, so you should do:

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    <define your constants here>
} else {
    <define your constants here>
}

See also this if you plan to support iOS versions previous to 3.2

Community
  • 1
  • 1
sergio
  • 68,819
  • 11
  • 102
  • 123
  • Thx - that is what I thought. But this method doesn't allow one to share the constants between classes does it? – Ghislain May 22 '11 at 21:46