Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UINavigationController back to more than one step

Is it possible to pop more than one viewcontroller in UINavigationController? suppose i want to go 2 steps back.

like image 436
taffarel Avatar asked Jun 10 '26 06:06

taffarel


2 Answers

Yes you could achieve that by doing something like

//Your navigation controller
UINavigationController *nav;

//Get the view controller that is 2 step behind
UIViewController *controller = [nav.viewControllers objectAtIndex:nav.viewControllers.count - 2];

//Go to that controller
[nav popToViewController:controller animated:YES];
like image 70
Omar Abdelhafith Avatar answered Jun 11 '26 18:06

Omar Abdelhafith


Swift

In swift the same solution presented by Omar is:

// Get the previous Controller.
let targetController: UIViewController = navigationController!.viewControllers[navigationController!.viewControllers.count - 2]

// And go to that Controller
navigationController?.popToViewController(targetController, animated: true)

In my case I need to back 2 controllers, so, I must to take the 3rd backing in stack. My real solution was:

// obtaining origin controller
let controller: UIViewController = navigationController!.viewControllers[navigationController!.viewControllers.count - 2]

// If was the expected controller (An enroll action)
if controller is CreateChatViewController {

    // I get the previous controller from it, in this case, the 3rd back in stack
    let newControllerTarget = navigationController!.viewControllers[navigationController!.viewControllers.count - 3]

    // And finally sends back to desired controller
    navigationController?.popToViewController(newControllerTarget, animated: true)
}
like image 44
Andre Cardoso Avatar answered Jun 11 '26 18:06

Andre Cardoso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!