美文网首页
iOS UIAlertController二次封装

iOS UIAlertController二次封装

作者: 劉光軍_MVP | 来源:发表于2018-11-21 17:12 被阅读48次

一:初始化

+ (instancetype)initDLAlertControllerWithTitle:(NSString *)title
                                       message:(NSString *)message
                                         style:(DLAlertStyle)style
                                      titleArr:(NSArray *)titleArr
                                    alerAction:(void (^)(NSInteger index))alerAction;
+ (instancetype)initDLAlertControllerWithTitle:(NSString *)title
                                       message:(NSString *)message
                                         style:(DLAlertStyle)style
                                      titleArr:(NSArray *)titleArr
                                    alerAction:(void (^)(NSInteger))alerAction {
    DLAlertController *alert = [DLAlertController alertControllerWithTitle:title message:message preferredStyle:style == 0 ? UIAlertControllerStyleActionSheet : UIAlertControllerStyleAlert];
    for (NSInteger i = 0; i < titleArr.count; i++) {
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:[titleArr objectAtIndex:i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (alerAction) {
                alerAction(i);
            }
        }];
        [alert addAction:confirm];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    [alert addAction:cancelAction];
    
    return alert;
}

二:弹出

- (void)showDLAlert {
    [[self getCurrentVC] presentViewController:self animated:YES completion:nil];
}

三:获取当前控制器

- (UIViewController *)getCurrentVC {
    UIViewController *result = nil;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow * tempWindow in windows) {
            if (tempWindow.windowLevel == UIWindowLevelNormal) {
                window = tempWindow;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    } else {
        result = window.rootViewController;
    }
    return result;
}

相关文章

网友评论

      本文标题:iOS UIAlertController二次封装

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