1

I have a custom PresentationViewController which has a half screen size height and full screen size width.

enter image description here

I want to press outside PresentationViewController to dismiss it.

I tried adding a button in under ViewController, but this button's action never be called.

I also tried adding a button in PresentationViewController that have frame equal to view.frame and send an action for touchUpOutside, this button's action never be called also.

So how to dismiss this PresentationViewController

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116

2 Answers2

1

add the gesture recognizer to the view's window

For Swift3

var recognizer = UITapGestureRecognizer(target: self, action: #selector(yourViewController.handleTap(_:)))
recognizer.numberOfTapsRequired = 1
recognizer.cancelsTouchesInView = false
self.view.window?.addGestureRecognizer(recognizer)

and call the function as like

 func handleTap(_ sender: UITapGestureRecognizer) {
if sender.state == .ended {
    var location: CGPoint = sender.location(in: nil)
    if !self.view.point(inside: self.view.convertPoint(location, from: self.view.window), withEvent: nil) {
        self.view.window?.removeGestureRecognizer(sender)
        self.dismiss(animated: true, completion: nil)
    }
}
}

for objective C you can take the reference from here

Community
  • 1
  • 1
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
0

In underViewController, I add a gesture like this:

self.tapGestureDismissTopFanVC = UITapGestureRecognizer(target: self, action: #selector(PlayDetailViewController.dismissTopFanVC(_:)))
self.view.window?.addGestureRecognizer(tapGestureDismissTopFanVC!) // not self.view.addGesture 
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)

then this gesture action:

func dismissTopFanVC(_ tapGesture: UITapGestureRecognizer) {
    if presentedViewController is TopFanPopOverViewController {
        presentedViewController?.dismiss(animated: true) {
            self.view.backgroundColor = .clear
            if self.tapGestureDismissTopFanVC != nil {
                self.view.window?.removeGestureRecognizer(self.tapGestureDismissTopFanVC!)
                self.tapGestureDismissTopFanVC = nil
            }
        }
    }
}
Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116