SuperDuperTango
SuperDuperTango

Reputation: 1408

How to programmatically show modal in a UINavigationController

In my app, I have a UINavigationController that i'm pushing and popping ViewControllers from. At some point, I want to show a VC modally (showing the previous controller "underneath"). I can get it to work by setting up a segue in a storyboard, however I'm in a spot where I need to do it programmatically, and I can't seem to find the right magic incantation to make it work.

I saw a couple of similar questions but they seemed to be showing the UINavigationController modally, not showing one of the VC's on the UINavigationController stack modally.

(I put up a test application here: https://github.com/SuperTango/ModalNavController, and that's where this code and images come from)

The "Manual" code does:

@IBAction func goToVC2Tapped(_ sender: Any) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let destinationViewController = storyboard.instantiateViewController(withIdentifier: "VC2ViewController") as! VC2ViewController
    destinationViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    self.navigationController?.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    self.navigationController?.pushViewController(destinationViewController, animated: true)
}

but it's not working (see the second transition in the gif below).

The segue that works is setup like this:

segue setup

This gif is from the test app and shows how it works with the segue, but not manually.

enter image description here

Any ideas? Thanks!

Upvotes: 2

Views: 4682

Answers (2)

vinay v
vinay v

Reputation: 1

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let destinationViewController = storyboard.instantiateViewController(withIdentifier: "YourVC") as! YourVC

destinationViewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext

destinationViewController.modalTransitionStyle = .crossDissolve

self.present(destinationViewController, animated: false, completion: nil)

I think this helps show your ViewController in a modal way of presenting. Write the above code under outlet actions or where you want to present your ViewController.

Upvotes: 0

Kevin
Kevin

Reputation: 493

To present modally you need to use:

present(destinationViewController, animated: true, completion: { })

Upvotes: 5

Related Questions