Reputation: 175
I have been working with modal view controllers for a while now but I was wondering whether or not there is a function to call to let the underlying view controller know that a modal view controller that has been overlaying it has been dismissed. If that is possible, how can you tell in a view controller that a modal view has been dismissed so that e.g. another modal view controller can be opened right after the old one has been dismissed? Thanks in advance
Upvotes: 0
Views: 5798
Reputation: 2206
This can be easily done using delegation.
Create a protocol in the modal view controller class(the view controller that is being presented).
protocol ModalViewControllerDelegate:class {
func dismissed()
}
Also create a delegate property and call the delegate method when the modal view controller is dismissed, say on tap of a button. Here is some code to help you with that.
class ModalViewController1: UIViewController {
var delegate:ModalViewControllerDelegate?
@IBAction func back(_ sender: Any) {
delegate?.dismissed()
}
}
Now in the presenting view controllers's prepare for segue method, make the presenting view controller as the delegate of the presented modal view controller. Heres some code.
import UIKit
class ViewController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "modal1" {
if let modalVC1 = segue.destination as? ModalViewController1 {
modalVC1.delegate = self
}
}
}
}
extension ViewController: ModalViewControllerDelegate {
func dismissed() {
dismiss(animated: true, completion: nil)//dismiss the presented view controller
//do whatever you want after it is dismissed
//like opening another modal view controller
}
}
The dismissed function will be called after the modal view controller's back button is tapped and you can dismiss the presented view controller and also proceed with whatever you want to do after that.
Upvotes: 9