Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss modal form sheet when clicking outside of view?

Tags:

ios

swift

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?

like image 692
user2980509 Avatar asked Dec 14 '22 03:12

user2980509


1 Answers

I had to display some screens like a popup in my app, so I've made a 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.

like image 80
Shurtugal Avatar answered Mar 08 '23 07:03

Shurtugal