Call storyboard scene programmatically (without needing segue)?

前端 未结 8 675
既然无缘
既然无缘 2020-12-04 10:10

I have a modal storyboard scene that I want to be accessible to all my other scenes. Creating a modal segue to it from every scene on my storyboard creates a big mess of str

相关标签:
8条回答
  • 2020-12-04 10:34

    Yes you can. Do something like this to get access to the VC, then just Modal Push it:

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
    MyNewViewController *myVC = (MyNewViewController *)[storyboard instantiateViewControllerWithIdentifier:@"myViewCont"];
    
    0 讨论(0)
  • 2020-12-04 10:35

    I have a case where I want to present a view controller from the main part of the app, one with settings & help & so on. To do this, I want it to be within a nav controller, sort of a little plug in module we can call from a UIBarButtonItem.

    Now, this can be to/in the current storyboard, or to another, it doesn't matter.

    I want to do it this way, because I loathe the potential of segue line spaghetti all over my storyboard.

    Here's how to do it.

    - (IBAction)displaySettings:(id)sender
    {
        LOG_SELECTOR() // google that for extra goodness
    
        // FYI, this can be done using a different storyboard like so.
        /*
         NSString * storyboardName = @"MainStoryboard_iPhone"; // possibly use device idiom?
         UIStoryboard * storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
         */
    
        // To push a new set of scenes with a new Navigation Controller, it is done like this:
        UINavigationController *settingsNC = [self.storyboard instantiateViewControllerWithIdentifier:@"Settings Nav Controller"];
        OBSettingsUIViewController *settingsVC = [self.storyboard instantiateViewControllerWithIdentifier:@"Settings root"];
        [settingsNC pushViewController:settingsVC animated:NO];
    
        [settingsNC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    
        // Present the view controller;
        [self presentViewController:settingsNC animated:YES completion:NULL];
    }
    

    In the presented view controllers (or in a subclass of the Navigation Controller), you can have a UIBarButtonItem to then dismiss the whole presented hierarchy of view controllers like so:

    - (IBAction)dismissThisVC:(id)sender {
         [self dismissViewControllerAnimated:YES completion:nil];
    }
    

    Hope this helps a bunch of people out. Cheers.

    0 讨论(0)
提交回复
热议问题