简体   繁体   中英

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.

PS If u can plz answer in swift.

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)
}

Add this line for your imageView because UIImageView default user interaction is disable. If you will enable UIImageView userinteraction then it will not work for your UIView and outside of UIImageView it will work

yourImage.userInteractionEnabled = YES;

Try this your tap clicked will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM