问题
I have created an additional iPad target for what was originally an iphone app.
From the Apple docs: "In nearly all cases, you will want to define a new view controller class to manage the iPad version of your application interface, especially if that interface is at all different from your iPhone interface. You can use conditional compilation to coordinate the creation of the different view controllers."
But they don't give any example or detail on what conditional compilation is. Can anyone give an example? And where would I do this?
EDIT: I have tried defining the following C Flags in the iPad target: -D USE_IPAD, -DUSE_IPAD. Either way, this code always results in IPHONE getting logged:
#ifdef USE_IPAD
NSLog(@"IPAD");
#else
NSLog(@"IPHONE");
#endif
What am I missing?
回答1:
Another approach which may be preferable to conditional compilation is a straight-forward if else statement:
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
// iPad code
} else {
// iPhone or iPod Touch code
}
I prefer this over conditional compilation as I find it easier to maintain and less line noise.
回答2:
Conditional compilation is where you use compiler directives (or compiler flags) to control compilation.
#ifdef SOME_CONDITION
//This will only be compiled if SOME_CONDITION is defined as a compiler flag
#else
//Otherwise, this code will compile.
#endif
You can define compiler directives in your projects settings. Right click on your Target (create multiple targets, one for iPhone and one for iPad, for example) and hit get info. Then scroll down to Other C Flags. You can add (a) flag(s) there.
EDIT:
It appears that I made the same mistake that you did. Some quick Googling leads me to the Apple documentation and this blog post which says that you may need to add a new field to the build settings.
来源:https://stackoverflow.com/questions/4581700/ios-conditional-compilation-xcode