Obj-C 以编程方式更改 ViewController(两个故事板)

Obj-C Change ViewController programmatically (Two storyboards)

首先,我想强调一下,这段代码是有效的,但看起来很糟糕。我需要以编程方式更改视图控制器(不能使用 segue),所以我使用此代码:

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

很明显它的工作原理。不幸的是,在创建第二个故事板 (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];

肯定有比这更好的解决方案,但我没有找到。你知道替代(更好)的解决方案吗?

保持你的 iPad 故事板名称与 iPhone 相同,只需在 '.storyboard' 之前附加 '~ipad' 并在 info.plist 中添加 'Main storyboard file base name (iPad)' 和将情节提要名称作为值。然后使用下面的代码根据设备获取故事板名称。

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

希望这会有所帮助。