2015-09-04 33 views
2

首先,我想强调一下,该代码正在工作,但看起来很糟糕。我需要以编程方式更改视图控制器(不能使用segue),所以我使用此代码:Obj-C以编程方式更改ViewController(两个故事板)

NSString *storyboardName = @"Main"; 
UIStoryboard *storyboard = 
    [UIStoryboard storyboardWithName:storyboardName bundle:nil]; 
PurchaseViewController *vc = [storyboard 
     instantiateViewControllerWithIdentifier:@"PurchaseViewController"]; 
[controller presentViewController:vc animated:YES completion:nil]; 

Obvoiusly其工作。不幸的是创建后第2个分镜(新iPad)我是被迫的代码更改为:

#define IDIOM UI_USER_INTERFACE_IDIOM() 
#define IPAD UIUserInterfaceIdiomPad 

/* 
    ... 
*/ 

NSString *storyboardName; 
if (IDIOM == IPAD) 
    storyboardName = @"Main_iPad"; 
else 
    storyboardName = @"Main"; 
UIStoryboard *storyboard = 
[UIStoryboard storyboardWithName:storyboardName bundle:nil]; 
PurchaseViewController *vc = [storyboard 
           instantiateViewControllerWithIdentifier:@"PurchaseViewController"]; 
[controller presentViewController:vc animated:YES completion:nil]; 

它必须比这更好的解决办法,但我没有找到一个。你知道替代(更好)的解决方案吗?

回答

2

enter image description here

让你的iPad故事板的名称相同之前iPhone '.storyboard' 加上 '〜iPad的' 在info.plist中添加 '主要故事板文件基本名称(新iPad)' 和将Storyboard名称作为值。然后使用下面的代码根据设备获取故事板名称。

NSBundle *bundle = [NSBundle mainBundle]; 
    NSString *storyboardName = [bundle objectForInfoDictionaryKey:@"UIMainStoryboardFile"]; 
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:storyboardName bundle:bundle]; 

希望这会有所帮助。

相关问题