Josh O'Connor Josh O'Connor - 1 year ago 65
Swift Question

Calling upon the previous view controller in Swift

I am trying to call upon the root controller and I don't know the code to call upon it. I'm using a conditional and which will check what the previous view controller was, and a block of code will run depending on what it was. Here is my code:


override func viewDidLoad ( ) {
super.viewDidLoad ( )

let previousController = storyboard!.instantiateViewControllerWithIdentifier ("firstViewController") as? FirstViewController

//if root view controller == previousController {
//run some code

Answer Source
let stack = self.navigationController.viewControllers
if (stack.count > 1) {
    let previousController = stack[stack.count-2]

Or if you don't have a navigation controller

let previousController = self.presentingViewController

Also, just to be clear, the root view controller will be the first view controller in the stack, i.e:



var previousController : UIViewController = self
var rootController : UIViewController?
do {
    var rootViewController = previousController
    var previousController = rootViewController.presentingViewController
} while (previousController != nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download