给UIAlertView添加手势使点击区域外弹框消失

给UIAlertView添加手势,点击alertView区域外使alertView消失。

- (void)disappearAlertView {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideAlertView:)];
//    tap.cancelsTouchesInView = NO;
    [[UIApplication sharedApplication].keyWindow addGestureRecognizer:tap];
}

- (void)hideAlertView:(UITapGestureRecognizer *)tap {
    if (tap.state == UIGestureRecognizerStateEnded){
        CGPoint location = [tap locationInView:nil];
        if (![self.alertView pointInside:[self.alertView convertPoint:location fromView:self.alertView.window] withEvent:nil]){
            [self.alertView.window removeGestureRecognizer:tap];
            [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
        }
    }
}

方法解释:

添加注释的那一行是因为alertView本身是没有点击事件的,加上手势之后也就只有一个点击事件,因此无所谓要不要限制触摸事件的传递。参考cancelsTouchesInView初见

  • (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event; // 判断point是否在接收者(此处指alertView)的区域内,一般是在的(返回为YES)

  • (CGPoint)convertPoint:(CGPoint)point fromView:(nullable UIView *)view; //将一个点转换为接收者,这个点位于给定的视图所在的坐标系中

  • (CGPoint)locationInView:(nullable UIView*)view; // 单点手势的位置,一般取的是触摸点的中心的位置。


后来发现:点击alertView按钮时,对于iOS7及以下的系统会直接触发手势响应方法,从而不再调用alertView的代理方法。
因此修改了以上代码。

/**
 *  需求:点击弹框之外的区域使得弹框消失
 *  实施:给keyWindow添加手势,使得点击弹框之外的区域时弹框消失
 */
- (void)buttonAlertView:(UIButton *)btn {

    self.alertView = [[UIAlertView alloc] initWithTitle:nil message:@"是否放弃此次操作?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [self.alertView show];

    self.recognizerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBehind:)];
    self.recognizerTap.cancelsTouchesInView = NO;
    [[UIApplication sharedApplication].keyWindow addGestureRecognizer:self.recognizerTap];

}

//手势响应方法-->使得弹框消失
- (void)handleTapBehind:(UITapGestureRecognizer *)sender {

    if (sender.state == UIGestureRecognizerStateEnded) {

        if (IOS8DEVICE) {
            [self removeTap];
        } else {
            //点击alertView按钮时,对于iOS7及以下的系统会直接触发手势响应方法,从而不再调用alertView的代理方法。因此延迟0.1s执行移除手势方法,即点击alertView按钮时能正确调用alertView的代理方法
            [self performSelector:@selector(removeTap) withObject:nil afterDelay:0.1f];
        }
    }
}

//移除手势
- (void)removeTap {
    [self.alertView.window removeGestureRecognizer:self.recognizerTap];
    [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
}

补充:

#define IOS8DEVICE [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值