4
votes

I don't know how exactly to achieve the following in Swift:

I am displaying a modal form sheet popup in my iPad app. In order to dismiss this view I have added a button that dismisses it. But what I really want is for it to dismiss when you click outside of the view. Almost the same behaviour as the popover. I have tried achieving this by adding tap gestures, making it a popover, any of the presentation styles, nothing works.

Has someone maybe done this so that you can point me in the right direction?

1
This post shows how to do it these days.LinusGeffarth

1 Answers

12
votes

I had to display some screens like a popup in my app, so i've made base class that looks like this:

class MyBasePopUp: UIViewController, UIGestureRecognizerDelegate {

var tap: UITapGestureRecognizer!
override func viewDidAppear(_ animated: Bool) {

    tap = UITapGestureRecognizer(target: self, action: #selector(onTap(sender:)))
    tap.numberOfTapsRequired = 1
    tap.numberOfTouchesRequired = 1
    tap.cancelsTouchesInView = false
    tap.delegate = self
    self.view.window?.addGestureRecognizer(tap)
}

internal func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

internal func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
    let location = touch.location(in: self.view)

    if self.view.point(inside: location, with: nil) {
        return false
    }
    else {
        return true
    }
}

@objc private func onTap(sender: UITapGestureRecognizer) {

    self.view.window?.removeGestureRecognizer(sender)
    self.dismiss(animated: true, completion: nil)
}

This is just to dismiss the popup, be careful if you have multiple gestures.