iOS UIAlertview(8.0之前) 点击空白让它消失
前言:UIAlertView在iOS 8.0 之后被废弃, 取而代之的是UIAlertControler, UIAlertView 苹果提供的接口并没有点击空白消失的方法, 在某些情况下我们需要在点击空白时, 让alertView 消失, 这里的思路是在alertView的widow层添加点击手势, 在点击时调用alertView的dismiss...方法
/**
弹出alertView的方法
@param message alertView - message
@param cancelTitle 关闭弹窗的按钮
*/
- (void)alertShowWithMessage:(NSString *)message cancelTitle:(NSString *)cancelTitle{
//保证每次都是初始化alert 防止多次调用弹窗信息不刷新
if (_alert) {
_alert = nil;
}
_alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:cancelTitle otherButtonTitles:nil, nil];
[_alert show];
//在alertView的window层添加点击手势
UITapGestureRecognizer *gestur = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
[_alert.window addGestureRecognizer:gestur];
}
/**
点击alertView的空白处让AlertView消失
@param sender 手势参数
*/
- (void)tapAction:(UITapGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateEnded) {
CGPoint location = [sender locationInView:nil];
if (![_alert pointInside:[_alert convertPoint:location fromView:_alert.window] withEvent:nil]) {
[_alert.window removeGestureRecognizer:sender];
//调用alertView消失的方法
[_alert dismissWithClickedButtonIndex:0 animated:YES];
}
}
}