【问题标题】:How to pass TouchUpInside event to a UIButton, without passing it to parent views?如何将 TouchUpInside 事件传递给 UIButton,而不将其传递给父视图?
【发布时间】:2012-01-22 00:07:31
【问题描述】:

我有一个启用分页的 UIScrollview。此滚动视图中有 3 个视图(页面)。在滚动视图的父视图上有一个点击手势,显示和隐藏顶部的导航栏。

问题: 在其中一个页面中,我想添加按钮。但问题是,每当我点击这些按钮时,也会触发显示/隐藏导航栏方法。将触摸仅传递给这些按钮而不是滚动视图的父视图的最佳方式是什么?

【问题讨论】:

    标签: objective-c uiscrollview gesture-recognition


    【解决方案1】:

    NJones 走在正确的轨道上,但我认为他的回答存在一些问题。

    我假设您希望通过滚动视图中的 any 按钮的触摸。在您的手势识别器的委托中,像这样实现gestureRecognizer:shouldReceiveTouch:

    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)recognizer shouldReceiveTouch:(UITouch *)touch {
    
        UIView *gestureView = recognizer.view;
        // gestureView is the view that the recognizer is attached to - should be the scroll view
    
        CGPoint point = [touch locationInView:gestureView];
        UIView *touchedView = [gestureView hitTest:point withEvent:nil];
        // touchedView is the deepest descendant of gestureView that contains point
    
        // Block the recognizer if touchedView is a UIButton, or a descendant of a UIButton
        while (touchedView && touchedView != gestureView) {
            if ([touchedView isKindOfClass:[UIButton class]])
                return NO;
            touchedView = touchedView.superview;
        }
        return YES;
    }
    

    【讨论】:

    • 太棒了!我想念他怎么说按钮复数。叮叮当当。我的答案是从我的其他答案之一复制而来的,这是要排除的一种观点。这对于倍数来说要好得多。
    • 我现在要试试这个。奇怪的是,我没有收到来自 * 的通知。但这看起来确实是一个可靠的解决方案。谢谢大家回复!