我想制作一个具有两个不同 XIB 文件的通用应用程序。一个用于 iPhone,一个用于 iPad。他们使用相同的代码,只是不同的用户界面。我将如何创建一个“通用”应用程序?
谢谢。
只需复制 xib 文件,然后将其重命名为FileName~ipad.xib,将其添加到您的项目中,iOS 将根据您的设备自动加载正确的 xib 文件。
As a start (you say you are creating a view based application), create it based upon either iPhone or an iPad view.
This will give you an appdelegate, a viewcontroller and a view (tailored for iPad or iPhone dependent upon which option you chose)
Now add another xib, go to File > New File... look on the left of the dialog and chooser "User Interface" in the iOS group. In the pane on the right, select View and click next, now choose iPad or iPhone (based on what you chose initially) when the xib is created, select it, then select the files owner on the left of the main pane. Then, go to Utilities (right pane) and choose Identity inspector (3rd option icon along the top) there change the class to be the same viewController as was created when you created your view based application. You can bind outlets just the same way on both views but they will share the same viewController.
Determining which device your app is running on at runtime, you can use the convention
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
and base the loading of views upon this kind of conditional statement. Just for clarity, remember you load a nib using its name so you can choose the nib relevant to the environment (above) and the framework will do the rest.
Be aware that it is never as straightforwards as you might think (if you've never done it before) Apps that make best use of the iPad's real estate generally tend to work better with dedicated views, although this is certainly not always the case. Any dynamically added screen components will need to be coded as such, taking into account the difference in screen space.
This could easily turn into an essay, I suggest you do some reading, check out source code and dive in. You'll learn a lot just by experimenting.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
UIInterfaceOrientation des=self.interfaceOrientation;
if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) //ipad
{
if (des==UIInterfaceOrientationPortrait||des==UIInterfaceOrientationPortraitUpsideDown)
{
//Ipad portarit
}
else
{
//ipad landscape
}
else //iPhone
{
if (des==UIInterfaceOrientationPortrait||des==UIInterfaceOrientationPortraitUpsideDown)
{
//iPhone portarit
}
else
{
//iPhone landscape
}
}
像这样创建一个宏:
#define IS_IPAD ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
为您的 XIB 命名,以便您可以执行此操作:
self.viewController = [[ViewController alloc] initWithNibName:IS_IPAD?@"ViewController~iPad":@"ViewController" bundle:nil];
如果您有现有的应用程序,那么 Targets-->upgrade for iPad/iPhone 中有选项
之后添加代码以检查应用程序是否在 iPad 或 iPhone 中运行。
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
//load xib of ipad
}
else
{
//load xib of iphone
}
您还可以使用 xcode 4 的功能。创建新项目时有一个选项,称为“通用应用程序”。基于此模板的应用程序使用上述分隔。你会得到 iphone 和 ipad 的文件夹,里面有视图。