问题
If I have a universal app (runs on both iPhone & iPad), how do I account for UI layout differences in code if the UI differs between the devices?
If I am using a XIB, I can simply load a different XIB depending on the device and use the same code. Correct?
If I am creating my UI programmatically, though, how should this be handled? Is there a better way than if/elsing my way through the code and looking at the device type? I understand it's doable this way, it just doesn't seem very elegant.
if (isiPhone)
{
UIView *myCommonView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 150.0, 50.0)];
myCommonView.backgroundColor = [UIColor colorWithPatternImage:iPhoneSpecificImage];
// bunch of other conditional code
}
else
{
UIView *myCommonView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 250.0, 150.0)];
myCommonView.backgroundColor = [UIColor colorWithPatternImage:iPadSpecificImage];
// bunch of other conditional code
}
回答1:
A much better alternative to using loads of if/else statements is to have multiple app delegates. An easy way to do this is to create an AppDelegate_iPhone & AppDelegate_iPad and respectively bind them (in IB) to the different XIBs that get loaded on launch. Now you have a way to programmatically add different items to each delegate.
This also can lead to an issue where you want to share UI elements between the delegates. In this case, you can create shared views that are used by both delegates (just import the view controller in both cases).
The code should structurally look something like this.
回答2:
Unfortunately, programmaticaly if/elsing is the only way to do this. But when you think of it it's not that bad. Apple allows you to produce 2 different apps from the same code for 2 different devices.
来源:https://stackoverflow.com/questions/5187870/iphone-sdk-how-to-account-for-ui-layout-differences-iphone-vs-ipad