swiftobjective-cviewcontroller

Swift navigating between viewcontrollers


Im looking for a word, method or similar for this situation. Say that i'm for example have 3 viewcontrollers, a, b and c.

And then i'm navigating from a to b and finally from b to c. From c then I want to dismiss my viewcontrollers all the way back to a. How do i achive this programmatically?


Solution

  • If you're using a UINavigationController you can use popToRootViewController

    import UIKit
    
    class AViewController: UIViewController {}
    class BViewController: UIViewController {}
    class CViewController: UIViewController {}
    
    let a = AViewController()
    let b = BViewController()
    let c = CViewController()
    
    let nav = UINavigationController(rootViewController: a)
    nav.pushViewController(b, animated: true)
    nav.pushViewController(c, animated: true)
    
    // Option 1
    nav.popToRootViewController(animated: true)
    
    // Option 2
    nav.popToViewController(a, animated: true)