简体   繁体   中英

Segue to a UINavigation Controller programmatically without storyboards

I have code that uses Storyboards for seques, like so:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"ShowDiagnosis"])
    {
        [segue.destinationViewController setHappiness:self.diagnosis];
    }
    ...

But I want to do it programmatically. I have myViewController class and when I click on a button I want to animate and push to myUINavigationController.

How is this done programmatically?

First things first, a segue cannot be created programmatically. It is created by the storyboard runtime when it is time to perform. However you may trigger a segue, which is already defined in the interface builder, by calling performSegueWithIdentifier: .

Other than this, you can provide transitions between view controllers without segue objects, for sure. In the corresponding action method, create your view controller instance, either by allocating programmatically or instantiating from storyboard with its identifier. Then, push it to your navigation controller.

- (void)buttonClicked:(UIButton *)sender
{
    MyViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"my-vc-identifier"];
    // OR MyViewController *vc = [[MyViewController alloc] init];

    // any setup code for *vc

    [self.navigationController pushViewController:vc animated:YES];
}

First of all segue can be used only with if you have a UINavigationController that will handle the navigation (push, pop, etc).

So if you have a UINavigationController and you want to push another UIViewController on the stack without using segue then you can use pushViewController:animated: method which also has a reverse popViewControllerAnimated: . Also UINavigationController provides other methods for adding/removing UIVIewControllers , for more info check UINavigationController class reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM