how to prevent a touch event passed to a UIView

2020-03-03 07:41发布

问题:

I've made a program which contains pictures that can be dragged to move on the screen. also I used UIScrollView since the space is larger than the window. I subclassed UIView as a pictures view to display the picture and handle touches in this class. picture views are added as subviews to the scrollView. but now I have a problem: when I drag the picture, the scrollView moves together with the picture. I'm wondering if there is a way to consume the touches in the picture class to prevent them from passing to superview.

回答1:

You should to put your code in "touchesMoved:withEvent:" method of your UIView. If your View will handle this event by yourself, then it should not bubble to superview



回答2:

Icewind's comment above solved the problem:

You can try to set canCancelContentTouches to NO in your UIScrollView. And set exclusiveTouch to YES in your UIView with image – icewind Mar 7 at 14:22



回答3:

why you use UIScrollView? You have you own scroll picture view so there is no need to use the UIScrollView to handle the scroll touch input.

other way around, why you use you own scroll picture view? UIScrollView will handle scrolling case so you can just put an UIImageView under UIScrollView which will work the same unless your own view have some other behaviour but you can subclassing UIImageView or UIView and no need to scroll the picture by you own because you know UIScrollView will do it for you.



回答4:

I know this is an old question, but I had a similar issue and the approved answer (setting canCancelContentTouches to false in the scroll view and isExclusiveTouch to true in the subview) did not work for me.

After some experimentation, I found that simply overriding gestureRecognizerShouldBegin(_:) in my subview to return false solved the problem:

override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    return false
}


回答5:

You need subclass UIScrollView and override touchesShouldCancel:

override func touchesShouldCancel(in view: UIView) -> Bool {
    return !(view is MyView) // or whatever your check is
}

As a bonus you may want to scrollView.delaysContentTouches = false for instant response on your custom controls.