Home > Enterprise >  How to dismiss ViewController in another View
How to dismiss ViewController in another View

Time:10-05

I want to dismiss my view controller in another view inside the button action.What I mean by that, I have a cancel Button inside UIView and I want to dismiss my viewController when I tapped to cancelButton. How can I do that?

 @objc func cancelButtonTapped() {
    
}

CodePudding user response:

I would recommend creating a delegate to reference the view controller you wish to dismiss:

protocol ViewDelegate {
    func dismissViewController()
}

Then make your view controller inherit this delegate and make sure to create a dismissViewController func to conform to the protocol:

class ViewController: UIViewController, ViewDelegate {
    func dismissViewController() {
        self.dismiss(animated: true, completion: nil)
    }
}

Lastly, pass a reference of this delegate to your view and use the dismissViewController func:

class CustomView: UIView {
     var delegate: ViewDelegate?


     @objc func cancelButtonTapped() {
        delegate.dismissViewController()
     }
}

CodePudding user response:

This SO question answers how to get to a UIViewController from a UIView using firstResponder. It's not recommended to do this.

Your other choices all center around some kind of pub/sub model. You could use NotificationCenter to publish a message that your UIViewController could listen for.

You could also use Combine and use some kind of publisher there to the same effect. A PassthroughSubject might be what you're looking for.

  • Related