Go back two levels with UINavigationController and Storyboard

I have a storyboard with three views of A, B and C (and more). From view B, the user can return to view A by clicking on the item in the left panel that is automatically created. I changed the label on this to "Cancel" by setting the Back Button property of the navigation item.

C should have the same Cancel button, but it makes no sense to return to viewing B; rather, it should return to A. I know how to do this programmatically, but where can I put the code so that it works when I click the Cancel button?

+3
source share
5 answers

B C A, -.

iOS:

, , , "" , .

, , . , , .

+1

, :

 [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];  
+8

, "". , , - , , .

, :

[self.navigationController viewControllers] objectAtIndex:1];

1 viewController, A rootView, :

[self.navigationController popToRootViewControllerAnimated:YES];
+2

, C, replace segue, .

+1

Another option: if you put the following in B, it will remove it from the stack when C is presented. Then the stack looks like [A,C], so it will go straight back to A.

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    // remove this view controller from the stack
    if let nav = self.navigationController {
        let vcs = nav.viewControllers.filter {(vc) in
            return (vc as? MyViewController) == nil
        }

        self.navigationController?.setViewControllers(vcs, animated: false)
    }
}
+1
source

All Articles