美文网首页iOS技术收藏
ios 中实现UIAlertController 点击背景区域后

ios 中实现UIAlertController 点击背景区域后

作者: 漫步在银河畔 | 来源:发表于2017-09-19 11:43 被阅读90次

    有时候需要实现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];

    ​ }];

    相关文章

      网友评论

      本文标题:ios 中实现UIAlertController 点击背景区域后

      本文链接:https://www.haomeiwen.com/subject/itjwsxtx.html