防止禁用的UIButton传播触摸事件

时间:2010-01-13 08:36:20

标签: iphone objective-c cocoa-touch event-handling uibutton

我的应用程序有两个重叠的UIButton。顶部按钮有时可能被禁用。但是,在这种情况下,它接收的任何触摸事件似乎都传递给底层视图,在我的情况下是另一个按钮。

我需要的是顶部按钮拦截所有触摸并阻止它们到达底部按钮,即使在禁用状态下(即使在禁用状态下调用指定的动作,我也会很高兴。)

到目前为止,我已经尝试过:

[topButton setUserInteractionEnabled:YES];

[topButton setExclusiveTouch:YES];

虽然后一种情况可能是不受欢迎的,因为如果点击了第一个视图,我仍然需要底部按钮来响应事件。无论哪种方式,它们都不起作用。

6 个答案:

答案 0 :(得分:14)

我在禁用按钮的超级视图中添加了以下方法:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if (!self.watchButton.enabled &&
        [self.watchButton pointInside:[self convertPoint:point toView:self.watchButton]
                            withEvent:nil]) {
        return nil;
    }
    return [super hitTest:point withEvent:event];
}

这适用于UITableView单元格。

答案 1 :(得分:4)

我设法通过上面@kolyuchiy的回复略微修改版本来实现这一点。我在我的hitTest:withEvent:子类中覆盖UIButton方法,在禁用时返回self并且该点在视图的框架内,以便消耗触摸,但不调用按钮的事件处理。

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    if ( !self.enabled && [self pointInside:[self convertPoint:point toView:self] withEvent:event] )
    {
        return self;
    }
    return [super hitTest:point withEvent:event];
}

答案 2 :(得分:3)

在尝试了@kolyuchiy(需要在其范围之外修改UIButton行为)和@ patrick-lynch(这对我不起作用)之后,解决方案更加优雅,适用于{{ 1}}子类:

UIButton

答案 3 :(得分:2)

我所做的是在UIButton下放置与UIButton相同大小的UIImageView。然后,即使您禁用UIButton,触摸事件也不会传播UIImageView。

答案 4 :(得分:2)

我知道这已经很晚了,但我正在阅读很多类似的问题,我读到的答案都没有对我有帮助(其中一些是因为没有工作和其他因为我不喜欢那个解决方案),所以我找到了一个更好的解决方案,我在这里分享它,以帮助未来阅读这个问题的用户。

<强>解决方案

我总是有一个容器里面有一些(或只有一个)按钮。因此,我将按钮容器的IBOutlet连接到我正在使用的UIViewControllerUIView

@property (weak, nonatomic) IBOutlet UIView *buttonsContainer;

我设置了一个零点击手势识别器,如下所示:

[self.buttonsContainer addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:nil]];

通过此解决方法,如果禁用了某个按钮,则buttonsContainer会捕获此事件并对其执行任何操作。

希望这有帮助。

答案 5 :(得分:1)

创建按钮的子类,然后覆盖这些方法,以便按钮捕获事件,但如果按钮的某些属性设置为NO,则忽略它们:

touchesBegan:withEvent:
touchesCancelled:withEvent:
touchesEnded:withEvent:
touchesMoved:withEvent:

这些是UIResponder的方法。

如果你想要处理事件,让他们只调用他们的[super ...]方法,否则就不要调用它,如果你想让事件“吃掉”就返回。

如果有必要,请参阅此内容:Observing pinch multi-touch gestures in a UITableView