Search code examples
iosobjective-csegueuinavigationitemuivewcontroller

How do I manually set the "Back" destination in iOS apps


I have a UIViewController called 'detailViewController'.

This view controller is accessed through multiple different segues using the push segue.

The problem I am facing is that the back button on the detailViewController takes the user back to the previous view controller (as it should), however I would like the back button to take the user to the masterViewController (the default UIViewController in the app).

How do I do this?

I have tried changing the segue types however that didn't really do anything at all.

Peter


Solution

  • The method you're looking for is UINavigationController's popToRootViewControllerAnimated:

    From the documentation: "Pops all the view controllers on the stack except the root view controller and updates the display."

    You'll need to create a custom back button. You can't afaik override the back button's functionality.

    So something like:

    UIButton *myBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [myBackButton addTarget:self action:@selector(popToRoot:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *myCustomBackButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myBackButton];
    [self.navigationItem setLeftBarButtonItem:myCustomBackButtonItem];
    

    and then the implementation of popToRoot: would look like:

    - (void)popToRoot:(id)sender
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }