【问题标题】:How To Detect "Touch Down" in superview of UIScrollView?如何在 UIScrollView 的超级视图中检测“Touch Down”?
【发布时间】:2011-02-05 11:20:39
【问题描述】:

我有一个包含UIScrollViewUIView,并且我希望能够在用户点击UIScrollView 的任何时候捕获UIView 中的“Touch Down”事件。

我已经尝试在我的UIViewController 中包含所有的 touchesBegan/Ended/Cancelled 处理程序,但是在主UIView 中包含的UIScrollView 内点击时,它们都不会被触发。

最好的方法是什么?

【问题讨论】:

    标签: ios objective-c uiview uiscrollview touch-event


    【解决方案1】:

    在 UIView 中,实现 touchesBegan:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        // assign a UITouch object to the current touch
        UITouch *touch = [[event allTouches] anyObject];
    
        // if the view in which the touch is found is myScrollView
        // (assuming myScrollView is the UIScrollView and is a subview of the UIView)
        if ([touch view] == myScrollView) {
            // do stuff here
        }
    }
    

    附注:确保在 UIView 中将 userInteractionEnabled 设置为 YES。

    【讨论】:

    • 并且,根据我下面的自我回答,为滚动视图设置用户 userInteractionEnabled=NO
    • 这违背了uiscrollview的目的,因为我们必须在“do stuff here”下实现滚动操作。
    【解决方案2】:

    你也可以在你的 UIView 子类中实现hitTest:withEvent:。调用此方法以确定哪个子视图应接收触摸事件。因此,您可以在这里只跟踪通过您的视图的所有事件,或者隐藏子视图中的一些事件。在这种情况下,您可能不需要禁用滚动视图的用户交互。

    UIView 类参考中查看有关此方法的更多详细信息。

    【讨论】:

      【解决方案3】:

      您还可以将手势识别器添加到您的超级视图。 例如,如果您需要激活/停用诸如覆盖滚动视图的按钮之类的东西,则需要点击手势:

      self.tap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)] autorelease];
      tap.numberOfTapsRequired = 1;
      
      ["containerView" addGestureRecognizer:tap];
      

      手势确实保留了滚动视图交互

      【讨论】:

      • tapgesturerecognizer 仅检测 TAPS (touchDown+touchUp)。所以现在我们想要检测 touchDown 事件。
      【解决方案4】:

      您需要禁用用户与滚动视图的交互...

      scrollView.userInteractionEnabled = NO;
      

      一旦禁用,UIScrollView 的 superview 就会获取 touchesBegan 事件。

      【讨论】:

      • 这违背了最初拥有滚动视图的目的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多