iosswiftmodal-view

Exit scene when clicking outside of modal view


Trying to exit the modal view to go back to the previous scene prior to selecting the modal view. Example attached below:

Select greyed out area

Originally I used some code from github to exit and return to the previous scene via button.

How can I select the greyed out part to exit instead?


Solution

  • Add a UITapGestureRecognizer to the gray view and set it up to a method that dismisses the view controller. E.g:

    let tap = UITapGestureRecognizer(target: self, action: "close:")
    grayView.addGestureRecognizer(tap)
    

    Put this in your viewDidLoad() for example. Then make the action that responds to the tap, in the global scope of the view controller:

    func close(tap: UITapGestureRecognizer) {
        self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
    }
    

    If you want the view to behave differently, you can try something like this:

    func close(tap: UITapGestureRecognizer) {
        let view = tap.view!
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            view.backgroundColor = UIColor.clearColor()
            }) { (success) -> Void in
                self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    

    You´ll maybe have to experiment with the duration of the animation to get it right.