前言
使用 UIAlertController 彈出對(duì)話框時(shí)构舟,想支持用戶(hù)點(diǎn)擊空白處能自動(dòng)隱藏對(duì)話框狭握。UIAlertControllerStyleActionSheet添加cancel按鈕即可實(shí)現(xiàn)。同樣的叼屠,UIAlertControllerStyleAlert即使添加cancel按鈕也不行瞳腌,下面,我們使用分類(lèi)給它添加自動(dòng)隱藏功能镜雨。
UIAlertController+HLTapDismiss.h
#import <UIKit/UIKit.h>
@interface UIAlertController (HLTapDismiss)
/// 彈窗點(diǎn)擊dismiss
- (void)alertTapDismiss;
@end
UIAlertController+HLTapDismiss.m
#import "UIAlertController+HLTapDismiss.h"
@interface UIAlertController ()<UIGestureRecognizerDelegate>
@end
@implementation UIAlertController (HLTapDismiss)
- (void)alertTapDismiss {
NSArray * arrayViews = [UIApplication sharedApplication].keyWindow.subviews;
if (arrayViews.count>0) {
//array會(huì)有兩個(gè)對(duì)象嫂侍,一個(gè)是UILayoutContainerView,另外一個(gè)是UITransitionView荚坞,我們找到最后一個(gè)
UIView * backView = arrayViews.lastObject;
backView.userInteractionEnabled = YES;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
tap.delegate = self;
[backView addGestureRecognizer:tap];
}
}
- (void)tap {
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
UIView *tapView = gestureRecognizer.view;
CGPoint point = [touch locationInView:tapView];
CGPoint conPoint = [self.view convertPoint:point fromView:tapView];
BOOL isContains = CGRectContainsPoint(self.view.bounds, conPoint);
if (isContains) {
// 單擊點(diǎn)包含在alert區(qū)域內(nèi) 不響應(yīng)tap手勢(shì)
return NO;
}
return YES;
}
@end
栗子
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"測(cè)試" message:@"測(cè)試一下" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"取消");
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"確定");
}]];
[self presentViewController:alert animated:YES completion:^{
// 添加點(diǎn)擊空白隱藏手勢(shì)
[alert alertTapDismiss];
}];