我有一个通用的应用程序,我手动加载我的主要故事板 application:didFinishLaunchingWithOptions
。
我有两个适用于iPhone和iPad的故事板 ~iPhone
和 ~iPad
后缀。我正在使用以下方式加载我的故事板:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
self.initialViewController = [storyboard instantiateInitialViewController];
这打印 Unknown class ViewController in Interface Builder file.
到控制台,显然它没有加载正确的故事板。但是,当我使用时 [UIStoryboard storyboardWithName:@"MainStoryboard~iPhone" bundle:nil];
它工作正常,但当然只适用于iPhone。
我错过了什么?如何使用名称后缀自动选择正确的故事板?
我不知道基于文件名后缀自动选择故事板。您可以使用 userInterfaceIdiom
选择iPad vs iPhone:
if ([[UIDevice currentDevice] userInterfaceIdiom] ==UIUserInterfaceIdiomPad) {
UIStoryboard *storyboard =
[UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil];
} else {
[UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
}
但是如果你这样做是为了启动一个特定的视图控制器,你需要做的就是将“开始”箭头拖到故事板中的首选视图控制器
或者 - 在故事板中选择视图控制器,转到属性instpector并勾选 isInitialViewController
这是您可以直接在info.plist文件中设置的另一件事。无需任何编程工作。寻找名为的财产 '主要故事板文件基本名称' 那将有 '主要' 在默认情况下。
您可以添加另一个名为的属性 '主要故事板文件基本名称(iPad)' 然后将用于iPad。
这就是plist中的原始输出看起来像:
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIMainStoryboardFile~ipad</key>
<string>iPad</string>
Afaik也可以简单地添加名为Main~iPad.storyboard的第二个故事板(如果UIMainStoryboardFile键设置为Main)。这将适用于iPad。虽然没有经过一段时间的测试。
//在appdelegate类中,启动应用程序时选择指定的故事板。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UIStoryboard *storyboard1;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
storyboard1 = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:[NSBundle mainBundle]];
}
else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
storyboard1 = [UIStoryboard storyboardWithName:@"Main_iPad" bundle:[NSBundle mainBundle]];
}
UIViewController *vc = [storyboard instantiateInitialViewController];
// Set root view controller and make windows visible
self.window.rootViewController = vc;
[self.window makeKeyAndVisible];
return YES;
}
你可以这样命名你的故事板
- Main.storyboard(适用于iPhone)
- Main_iPad.storyboard(适用于iPad)
然后像这样选择它们
- (UIStoryboard *)deviceStoryboardWithName:(NSString *)name bundle:(NSBundle *)bundle {
if (IS_IPAD) {
NSString *storyboardIpadName = [NSString stringWithFormat:@"%@_iPad", name];
NSString *path = [[NSBundle mainBundle] pathForResource:storyboardIpadName ofType:@"storyboardc"];
if (path.length > 0) {
return [UIStoryboard storyboardWithName:storyboardIpadName bundle:bundle];
}
}
return [UIStoryboard storyboardWithName:name bundle:bundle];
}