Reputation:
I have a Storyboard with three views A, B and C (and more). From view B, the user can go back to view A by tapping the left button bar item that's automatically created. I've changed the label on this to "Cancel" by setting the Back Button property of A's navigation item.
C should have the same Cancel button, but it doesn't make sense to go back to view B; rather it should jump back to A. I know how to do this programatically but where do I put the code so it's triggered when C's Cancel button is tapped?
Upvotes: 3
Views: 4203
Reputation: 16059
Another option: if you put the following into B, it will remove it from the stack when C is presented. Then the stack looks like [A,C]
so back will go straight 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)
}
}
Upvotes: 0
Reputation: 3730
I found this way simplest, just put index:
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
Upvotes: 9
Reputation: 8570
If you want to cancel an action from B or C and go back to A it may make more sense to present the view controllers modally.
From the iOS human interface guidelines:
A modal view generally displays a button that completes the task and dismisses the view, and a Cancel button users can tap to abandon the task.
Use a modal view when you need to offer the ability to accomplish a self-contained task related to your application’s primary function. A modal view is especially appropriate for a multistep subtask that requires UI elements that don’t belong in the main application user interface all the time.
Upvotes: 1
Reputation: 2344
I think you cannot override the back button function. What I do in those cases, is create a left bar item and on it's function decide which navigationController view to send the user to.
I do that by using:
[self.navigationController viewControllers] objectAtIndex:1];
Index 1 will be the first view after the root viewController, if A is your rootView, you can also use:
[self.navigationController popToRootViewControllerAnimated:YES];
Upvotes: 3
Reputation: 25740
Instead of pushing C, use the replace option in the segue so that it will do this automatically for you.
Upvotes: 1