Present and dismiss modal view controller
Swift
Updated for Swift 3
Storyboard
Create two View Controllers with a button on each. For the second view controller, set the class name to SecondViewController
and the storyboard ID to secondVC
.
Code
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBAction func presentButtonTapped(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myModalViewController = storyboard.instantiateViewController(withIdentifier: "secondVC")
myModalViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
myModalViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(myModalViewController, animated: true, completion: nil)
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
@IBAction func dismissButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
Source:
- Documentation
- SO answer
First of all, when you put that code in applicationDidFinishLaunching, it might be the case that controllers instantiated from Interface Builder are not yet linked to your application (so "red" and "blue" are still nil
).
But to answer your initial question, what you're doing wrong is that you're calling dismissModalViewControllerAnimated:
on the wrong controller! It should be like this:
[blue presentModalViewController:red animated:YES];
[red dismissModalViewControllerAnimated:YES];
Usually the "red" controller should decide to dismiss himself at some point (maybe when a "cancel" button is clicked). Then the "red" controller could call the method on self
:
[self dismissModalViewControllerAnimated:YES];
If it still doesn't work, it might have something to do with the fact that the controller is presented in an animation fashion, so you might not be allowed to dismiss the controller so soon after presenting it.