Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - Close current ViewController and Open new ViewController

I've gone through a tad amount of SO posts about this but none of them clearly state how to get this done in Swift 3.

Simply put, I need to close the current view that is displayed and open a new view controller. Such that the only view controller open would be the 2nd VC

This is the code I tried using, but when I try this the view controller gets closed without the rest of the code getting executed

//Close current VC
self.dismiss(animated: true, completion: nil)

//Open the new VC
let mainStoryboard: UIStoryboard = UIStoryboard(name:"Main",bundle:Bundle.main)
let secondViewController: SecondViewController = mainStoryboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
self.present(secondViewController, animated: true, completion: nil)

Can someone help me out? I just need a simple transition from 1st VC to 2nd VC and close the 1st VC.

like image 965
Dinuka Jay Avatar asked Jun 05 '26 03:06

Dinuka Jay


1 Answers

The problem is, that "self" can not present the new ViewController since it is the ViewController that is getting dismissed.

You could try calling self.presentingViewController?.present(secondViewController, animated: true, completion: nil)

like image 167
d.felber Avatar answered Jun 08 '26 00:06

d.felber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!