Dismissing popup view tapping outside

class MyView < UIVIewController

  ...

  # set gesture to close
  def viewDidAppear(animated)
    recognizer = UITapGestureRecognizer.alloc.initWithTarget(self, action: 'handleTapBehind:')

    recognizer.setNumberOfTapsRequired(1)
    recognizer.cancelsTouchesInView = false
    self.view.window.addGestureRecognizer(recognizer)
  end

  # handle tap  
  def handleTapBehind(sender)
    if sender.state == UIGestureRecognizerStateEnded
      location = sender.locationInView(nil)
      unless self.view.pointInside(self.view.convertPoint(location, fromView: self.view.window), withEvent: nil)
        self.view.window.removeGestureRecognizer(sender)
        self.dismissViewControllerAnimated(true, completion: lambda{})
      end
    end
  end

end

 

Leave a Reply

Your email address will not be published. Required fields are marked *

× 7 = 28