How to get the link to the previous viewController in Swift?

Can someone help me get a link to the previous one viewControlleron the stack UINavigationController? I am sure it is straight forward, but I knocked a bit at the moment.

enter image description here

+6
source share
6 answers

The first array of things always starts with index 0, so you need minus 2 to access the previous one. Also, the code above will fail Array index out of Rangeif your access object index is less than your account. so check your condition as follows

let count = viewControllers?.count
if count > 1 {
    if let setVC = viewControllers?[count -2] as? SWSetVC {
        //Set the value
    }
}
+10
source

You can also use this:

(using quick 3)

 let i = navigationController?.viewControllers.index(of: self)
 let previousViewController = navigationController?.viewControllers[i!-1]
+5
source
let count = self.navigationController.viewControllers.count;
self.navigationController.viewControllers[count - 2];
+1

, controllers[count - 2], controllers[count - 1].

0

:

extension Array where Iterator.Element == UIViewController {

    var previous: UIViewController? {
        if self.count > 1 {
            return self[self.count - 2]
        }
        return nil
    }

}

, VC :

if self.navigationController?.viewControllers.previous is CustomVC {
    ...
} else {
    ...
}
0

I like to use the function below to get a link to any UIViewControllerin the navigation stack. If there is no such link, it simply returns nil.

extension UINavigationController {

    func getReferenceTo<ViewController: UIViewController>(viewController: ViewController.Type) -> ViewController? {
        return self.viewControllers.first { $0 is ViewController } as? ViewController
    }
}

Use Case:

func tappedBackToHomeButton() {
    guard let homeVC = self.navigationController?.getReferenceTo(viewController: HomeVC.self) else { return }
    // Pass variables if needed.
    self.navigationController?.popToViewController(homeVC, animated: true)
}
0
source

Source: https://habr.com/ru/post/1648588/


All Articles