How to dismiss viewcontroller and pop to root viewcontroller swift?

489 Views Asked by At

I have main TabbarController which holds ViewController(A). From this A pushed another ViewController(B) using navigationController?.pushViewController From B pushed another ViewController(C) using navigationController?.pushViewController From C modally presented another ViewController(D). From D when use taps button , it should dismiss D and popToRootViewController .

I googled similar questions, but couldn't find solution yet.

How can I do this?

1

There are 1 best solutions below

5
Elhoej On BEST ANSWER

Create a protocol

protocol YourDelegate: class {
    func didDismiss()
}

In ViewController D, create a weak reference to the protocol

weak var delegate: YourDelegate?

In ViewController C, conform to the protocol and popToRootVC in the function

extension ViewControllerC: YourDelegate {
    func didDismiss() {
        self.navigationController?.popToRootViewController()
    }
}

Also in ViewController C, set ViewControllerD's delegate to self where you present the VC

//example:
let vcD = ViewControllerD()
vcD.delegate = self
self.navigationController.pushViewController(vcD, animated: true)

At last, in ViewController D, in your dismiss function closure, call the delegate function

self.dismiss(animated: true) {
    self.delegate?.didDismiss()
}