Whenever the back button is pressed on my top view controller I want to go back to a specific view controller that is not the previous view controller. I was hoping there was a way to override the functionality of the back button in some way.
EDIT:
I got this to work:
self.navigationController?.popToRootViewController(animated: true)
The only issue is as it is animating it shows the intermediate view controller as its going to the root.
Reading your edited question, it seems that what you are looking for is to pop back to the root view controller in the navigation stack without the animation revealing any view controllers in between.
You can easily achieve this by removing all those middle view controllers from the stack.
In the viewDidLoad
method of your last shown view controller do:
func viewDidLoad() {
super.viewDidLoad()
if let rootVC = navigationController?.viewControllers.first {
navigationController?.viewControllers = [rootVC, self]
}
}
Then, when tapping on the back button, the navigation controller will dismiss the current view controller going back to the root.
Based on apple developer documentation:
A navigation controller object manages its child view controllers using an ordered array, known as the navigation stack. The first view controller in the array is the root view controller and represents the bottom of the stack. The last view controller in the array is the topmost item on the stack, and represents the view controller currently being displayed. You add and remove view controllers from the stack using segues or using the methods of this class.
for achieving the pop without animation you should do:
var viewControllers: [UIViewController] The view controllers currently on the navigation stack.
example:
yourViewController.navigationController.viewControllers = [specificVC,self]
import UIKit
extension: UIViewController {
func setNext(to root: UIViewController? = nil) {
guard let navigation = self.navigationController,
let first = navigation.viewControllers.first else {return}
if let root = root {
navigation.viewControllers = [root,self]
}else{
navigation.viewControllers = [first,self]
}
}
}
self.setNext(to: specificVC)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With