UIAlertController 點擊背景消失或隱藏

UIAlertController 的使用方法這里就不介紹了 .

直接上思路,UIAlertController類比一個控制器.我們在顯示UIAlertController時用到
[self presentViewController:alertController animated:YES completion:nil];

我們可以在模態(tài)進去之后添加一個點擊手勢.執(zhí)行點擊時就把自己隱藏起來.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;

這樣子就行了.趕緊去試試吧

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容