Search code examples
iosuiviewuiimageviewtap

Tap recognizer around UIImageView


Good day, I have UIImageView inside UIView and I want to handle event, when user tap on UIView background, but not on UIImageView. How can I achieve it? I read about UITapGestureRecognizer, but it confuse me a little.

P.S. If u can plz answer in swift.


Solution

  • If you want to disable UITapGestureRecognizer on the child view of your main view then you have to enable User Interaction of your UIImageView like this

    imgTest.userInteractionEnabled = true;
    

    then you have to set the Delegate of your UITapGestureRecognizer to detect the UITouch of the view, set the delegate like this

    let touch  = (UITapGestureRecognizer(target: self, action: "tapDetected:"))
    touch.delegate = self
    self.view.addGestureRecognizer(touch)
    

    Then you have to implement the Delegate method of UITapGestureRecognizer in which you will detect the view which is currently touched like this

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
        if touch.valueForKey("view")!.isKindOfClass(UIImageView) {
            return false
        } else {
            return true
        }
    }
    

    In the above code i have disable the tap gesture on UIImageView

    Now, this method will work only for your self.view not for UIImageView

    func tapDetected(sender: UITapGestureRecognizer) {
            self.dismissViewControllerAnimated(false, completion: nil)
    }