Search code examples
iosobjective-ciphoneuiviewcontrollerxcode-storyboard

Obj-C Change ViewController programmatically (Two storyboards)


First of all, I want to highlight, that this code is working, but bad-looking. I need to change view controller programmatically (can't use segue), so I use this code:

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

Obvoiusly its working. Unfortunately after create 2nd storyboard (iPad) I was forced to change this code to:

#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];

It must be better solution than this, but I didn't found one. Do you know alternative(better) solution?


Solution

  • enter image description here

    Keep your iPad Storyboard name same as iPhone just append '~ipad' before '.storyboard' and add 'Main storyboard file base name (iPad)' in info.plist and put Storyboard name as value. Then use below code to get storyboard name according to device.

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

    Hope this will help.