2015-09-04 63 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]; 

希望這會有所幫助。

相關問題