How can a superview interecept a touch sequence before any of its subviews?

六月ゝ 毕业季﹏ 提交于 2019-12-19 10:18:19

问题


I have a view hierarchy that is layed out as follows:

parentView

 scrollView

    contentViewA

    containerView

         contentViewB

         contentViewC

I want contentViewB to respond to touches. Unfortunately scrollView makes this almost impossible because it tries to ingest the touches itself making touch response of contentViewB spotty.

So, instead, I want to intercept all touches in the parentView, manipulate contentViewB directly, and then pass the touches on to scrollView so it can do its thing.

Can someone please show me the correct way to pull this off?

Thanks in advance.

Cheers, Doug

UPDATE:

I did a bit more digging and found the property canCancelContentTouches which seems to work wonders. I'm using IB so I unchecked "Cancellable Content Touches" in IB - first tab of the Scroll View Attribute Inspector. Now, when I run the app, touches appear to be arriving at contentViewB reliably.

Here's how the UIScrollView docs describe this property:

Discussion If the value of this property is YES and a view in the content has begun tracking a finger touching it, and if the user drags the finger enough to initiate a scroll, the view receives a touchesCancelled:withEvent: message and the scroll view handles the touch as a scroll. If the value of this property is NO, the scroll view does not scroll regardless of finger movement once the content view starts tracking.

Rather opaque huh? Anyway, it seems to work.


回答1:


To stop the scroll view from intercepting the touch events, set the userInteractionEnabled property like so:

scrollView.userInteractionEnabled = NO;



回答2:


Another way of doing this is to add another subview to your ui so it looks like so :

parentView
  scrollView
    contentViewA
      containerView
        contentViewB
        contentViewC
  touchGrabber

and, in touchGrabber, detect all the touches that you want (by subclassing UIView)

This is more complicated than Phil Nash's solution but has the advantage that you can add/remove other views from your parentView without having to deal with their userInteractionEnabled value - this is useful if you have a third party library adding views for example.

However, if you definately only going to have the scrollView, Phil Nash's answer is the way forward!

Thanks,

Sam



来源:https://stackoverflow.com/questions/1673903/how-can-a-superview-interecept-a-touch-sequence-before-any-of-its-subviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!