iOS点击事件和手势冲突

场景:

1.父视图添加了左划手势,触发返回方法

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self 
                                                                             action:@selector(statusBack)];
[self.view addGestureRecognizer:panGesture];

2.子视图添加了UIButton

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundColor:[UIColor colorWithHexString:@"12aaff"]];
    [button setTitle:NSLocalizedString(@"creat_wallet_confirm", nil) forState:UIControlStateNormal];
    [button setTitleColor:MOWhiteColor forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:16]];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 3;
    [button addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:button];

出现的结果bug:

每次点击确认按钮的时候,会触发左划手势,导致手势和触发方法同时运行,pop出当前页面。

解决方法:

当前页面添加 UIGestureRecognizerDelegate 声明
 panGesture.delegate = self
#pragma mark - UIGestureRecognizer delegate -
/*- 解决左划手势和确认按钮冲突bug -*/
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    // 若为UIButton
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UIButton"]) {
        // UIButton 不需要响应 父视图的手势,保证出发方法 可以正常
        return NO;
    }
    //默认都需要响应
    return  YES;
}

参考:
https://www.jianshu.com/p/53e03e558cbd

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容