开发者

how to prevent a touch event passed to a UIView's superview?

开发者 https://www.devze.com 2023-02-15 10:08 出处:网络
I\'ve made a program which contains pictures that can be dragged to move on the screen. also I used UIScrollView sin开发者_运维问答ce the space is larger than the window.

I've made a program which contains pictures that can be dragged to move on the screen. also I used UIScrollView sin开发者_运维问答ce 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.


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


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
}


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消