UIView添加手势,UIbutton不响应点击事件

/避免添加在view上的手势使button的UIControlEventTouchUpInside不响应
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return ([[touch.view class] isSubclassOfClass:[UIButton class]]) ? NO : YES;
}
 
//添加手势
- (void)setTheGesture {
 
    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    UIView *myView = [self.view viewWithTag:1];
    [myView addGestureRecognizer:singleTap];
}
 
//此方法来自于 <http://www.devdiv.com/forum.php?mod=viewthread&action=printable&tid=101367>
/*
So while working on version 2.0 of Today's News, we came across the need to have a UIButton as a subview of a view which handles tap gestures. So the expected behavior is that if we tap inside the button, it should fire the corresponding selector for the UIControlEventTouchUpInside event, but otherwise it should fire the selector for the tap gesture recognizer. Unfortunately, it doesn't work that way by default.
*/
/*I found two solutions on Stack Overflow:
Solution 1: Is to set the cancelsTouchesInView property for UITapGestureRecognizer. While this works, what happens is that the selector for the tap gesture is fired along with the selector for UIControlEventTouchUpInside - not ideal.
Solution 2: Is what I chose, because it lets you decide whether the touch should be ignored or not. So as the Gist below describes, if the view corresponding to the touch is a subview of UIButton, then ignore, otherwise don't ignore.
*/
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
  return ([[touch.view class] isSubclassOfClass:[UIButton class]]) ? NO : YES;
}
/*
其实你响应的 有可能不是UIButton,但没事,你可以根据[touch.view class]的打印来判断,类似这样,一个UIBarButtonItem显示的却是UIToolbarTextButton
*/
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([[NSString stringWithFormat:@"%@",[touch.view class]] isEqualToString:@"UIToolbarTextButton"]) {
        return NO;
    } else {
 
        return YES;
    }
    //return ([[touch.view class] isSubclassOfClass:UIToolbarTextButton]) ? NO : YES;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值