Home > Mobile >  Swift - How to dismiss previous View Controller or a controller that i want from another View Contro
Swift - How to dismiss previous View Controller or a controller that i want from another View Contro

Time:10-28

I want to dismiss a view controller that is not currently on top.

I present a view controller and when i present it i want the previous one closed.

To give more details, This is the path i follow A -> B -> C when i reach the C I want B to be closed.

CodePudding user response:

In addition to the other answer here you can use

navigationController.viewControllers.remove(at: 1)

Edit:

You can use UINavigationController to control the stack of your ViewControllers.

let viewControllerA = UIViewController()
let viewControllerB = UIViewController()
let viewControllerC = UIViewController()
let navigationController = UINavigationController(rootViewController: viewControllerA)
navigationController.pushViewController(viewControllerB, animated: true)
navigationController.pushViewController(viewControllerC, animated: true)
// Remove B
navigationController.viewControllers.remove(at: 1)

CodePudding user response:

It depends a little on how you are doing your navigation. If you are using a navigation controller, you can access the array of view controllers and manipulate that directly. For example,

navigationController.viewControllers.popLast() //removes the last view controller and gives you a reference to it if you need.

If you are using segues, you could segue back to viewController A before moving to C.

You can also manipulate the viewController stack in other ways using this.

You can also ask a view controller to dismiss itself using self.dismiss(animated: true).

If you are interested, I find Coordinator Pattern a really good way to solve a lot of navigation issues is iOS.

If you want to post some code, I can take a closer look at it for you.

CodePudding user response:

You can use presentingViewController property of UIViewController to access VC that presented this VC. This way u can dismiss previous VC.

/// lets present vc2 from vc 1
let vc1 = UIViewController()
let vc2 = UIViewController()
vc1.present(vc2, animated: true)
        
/// presentingViewController of vc2 will be vc1, and it will dismiss if presented modally.
vc2.presentingViewController?.dismiss(animated: true)
  • Related