UIAlertController 点击背景消失或隐藏
2018-11-15 本文已影响0人
Kingiiyy_iOS
UIAlertController 的使用方法这里就不介绍了 .
直接上思路,UIAlertController类比一个控制器.我们在显示UIAlertController时用到
[self presentViewController:alertController animated:YES completion:nil];
我们可以在模态进去之后添加一个点击手势.执行点击时就把自己隐藏起来.Perfect
做一个UIAlertController 的分类. 先声明
@interface UIAlertController (Extension)
-(void)tapGesAlert;
方法实现
-(void)tapGesAlert
{
NSArray * arrayViews = [UIApplication sharedApplication].keyWindow.subviews;
if (arrayViews.count>0) {
//array会有两个对象,一个是UILayoutContainerView,另外一个是UITransitionView,我们找到最后一个
UIView * backView = arrayViews.lastObject;
//我们可以在这个backView上添加点击事件,当然也可以在其子view上添加,如下:
// NSArray * subBackView = [backView subviews];
// backView = subBackView[0]; 或者如下
// backView = subBackView[1];
backView.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(CancelAlert)];
[backView addGestureRecognizer:tap];
}
}
-(void)CancelAlert
{
[self dismissViewControllerAnimated:YES completion:nil];
}
接下来需要注意的是.
[self presentViewController:alertController animated:YES completion:nil];
// 以往使用的要换成下边的.才能完成添加手势
[self presentViewController:alertController animated:YES completion:^{
[alertController tapGesAlert];
}];
//还有.也可以把取消事件开放出来
@interface UIAlertController (Extension)
-(void)tapGesAlert;
-(void)CancelAlert;
这样子就行了.赶紧去试试吧