iOS之UIAlertViewController精简使用

以前的UIAlertView可以随时调用,不用担心在哪个控制器调用,iOS10出现以后,基本上不再对7进行适配了,所以UIAlertView也逐渐UIAlertViewController取代了,而UIAlertViewController的使用需要拿到当前视图,并在当前视图模态弹出UIAlertViewController。所以要实现一句话调用alert的关键就变成了如何拿到当前视图。

获取当前视图

1.如果当前视图在rootViewController的navgationController的堆栈中,我们就可以通过直接拿到rootViewController,来弹出UIAlertViewController。如下:

UIWindow *window = [[UIApplication sharedApplication].delegate window];
 [window.rootViewController presentViewController:alertVC animated:YES completion:nil];

2.如果当前视图不在navgation的堆栈中,当前视图也是模态弹出的,我们可以通过rootViewController的presentedViewController来弹出UIAlertviewController。如下:

 UIWindow *window = [[UIApplication sharedApplication].delegate window];
 [[[window rootViewController] presentedViewController] presentViewController:alertVC animated:YES completion:nil];

一句话调用

综合以上两种情况,我们可以实现类似于UIAlertView的一句话调用UIAlertViewController。
1.SQAlert.h文件

#import 
#import 

typedef void(^SQAlertConfirmHandle)();
typedef void(^SQAlertCancleHandle)();

@interface SQAlert : NSObject

+ (void)showAlertWithTitle:(NSString *)title message:(NSString *)message confirmHandle:(SQAlertConfirmHandle)confirmHandle cancleHandle:(SQAlertCancleHandle)cancleHandle;

@end

2.SQAlert.m文件

#import "SQAlert.h"

@implementation SQAlert

+ (void)showAlertWithTitle:(NSString *)title message:(NSString *)message confirmHandle:(SQAlertConfirmHandle)confirmHandle cancleHandle:(SQAlertCancleHandle)cancleHandle {
   UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (cancleHandle) {
            cancleHandle();
        }
    }];
    UIAlertAction *confirAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (confirmHandle) {
            confirmHandle();
        }
    }];
    [alertVC addAction:cancleAction];
    [alertVC addAction:confirAction];
    [[SQAlert currentViewController] presentViewController:alertVC animated:YES completion:nil];
}

+ (UIViewController *)currentViewController {
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    UIViewController *presentedVC = [[window rootViewController] presentedViewController];
    if (presentedVC) {
        return presentedVC;

    } else {
        return window.rootViewController;
    }
}

@end

3.使用方式:

#import "SQAlert.h"
[SQAlert showAlertWithTitle:nil message:@"hello" confirmHandle:nil cancleHandle:nil];

效果如下:
iOS之UIAlertViewController精简使用_第1张图片

你可能感兴趣的:(IOS专栏)