有时候需要实现UIAlertController 点击背景区域后退出消失的功能,默认情况下,UIAlertController不支持,我们可以在UIAlertController中添加category,添加一个方法,实现点击退出的功能!直接上代码
.h实现
#import <UIKit/UIKit.h>
@interface UIAlertController (TapGesAlertController)
- (void)tapGesAlert;
@end
.m 实现
#import "UIAlertController+TapGesAlertController.h"
@implementation UIAlertController (TapGesAlertController)
- (void)tapGesAlert{
NSArray * array = [UIApplication sharedApplication].keyWindow.subviews;
if (array.count>0) {
// 查找第1个元素位置,即为灰色背景,对其添加点击事件
UIView * backView = array[1];
backView.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
[backView addGestureRecognizer:tap];
}
}
-(void)tap
{
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
注意:使用的时候,我习惯在completion中实现这个方法,
[self presentViewController:alertController animated:YES completion:^{
[alertController tapGesAlert];
}];
网友评论