代码:
封装部分:
#pragma - mark - AlertController 封装
+(void)showCyAlertInController:( UIViewController * __nullable) controller
Title:(NSString * __nullable)title
Message:(NSString * __nullable)message
ButtonsTitleArray:(NSArray *)buttonsTitleArray
Handler:(void (^)(int selectedIndex))handler
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert ];
//空按钮集合
if (buttonsTitleArray.count<1) {
return;
}
//分配事件
for (int i=0; i<buttonsTitleArray.count; i++) {
NSString *btnTitle=buttonsTitleArray[i];
UIAlertAction *actions = [UIAlertAction actionWithTitle:btnTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
NSLog(@"选择了:%@",btnTitle);
handler(i);
}];
[alertController addAction:actions];
}
//获取根控制器进行跳转弹出事件
UIViewController *rootViewController=[UIApplication sharedApplication].keyWindow.rootViewController;
rootViewController=controller==nil?rootViewController:controller;
//查看根控制器是否已推出控制器,如果有,在已推出控制器消失前,无法推出新的控制器。
UIViewController *presentedVC=rootViewController.presentedViewController;
if (presentedVC) {
NSLog(@"已经有一个推出的控制器:%@",[presentedVC class]);
// [presentedVC dismissViewControllerAnimated:YES completion:nil];
}
[rootViewController presentViewController:alertController animated:YES completion:nil];
}
使用部分:
[CyloHelper showCyAlertInController:nil
Title:@"标题"
Message:@"你的银行卡里面的钱谁拿走的?"
ButtonsTitleArray:@[@"你邻居二姐",@"你哥",@"你大爷"]
Handler:^(int selectedIndex){
switch (selectedIndex) {
case 0:
NSLog(@"弄她!");
break;
case 1:
NSLog(@"弄他!");
break;
case 2:
NSLog(@"弄Ta!");
break;
default:
break;
}
}];
效果: