iOS_UIAlertController的使用方法

时间:2021-02-06 05:17:05

iOS 8新增加了UIAlertController控制器,用之前的UIAlertview和actionSheet会报警告,这个控制器可以实现警告框和操作表,非常的方便。使用UIAlertController的优势在于不仅可以添加按钮,还可以添加文本框和自定义视图到警告框和操作表中;相应时间可以通过闭包实现,而不用委托协议实现。下面我就介绍UIAlertController的基本使用方法。

-(void)creatAlertController_sheet {

/*
先创建UIAlertController,preferredStyle:选择UIAlertControllerStyleActionSheet,这个就是相当于创建8.0版本之前的UIActionSheet;

typedef NS_ENUM(NSInteger, UIAlertControllerStyle) {
UIAlertControllerStyleActionSheet = 0,
UIAlertControllerStyleAlert
} NS_ENUM_AVAILABLE_IOS(8_0);

*/
UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"标题" message:@"注释信息,没有就写nil" preferredStyle:UIAlertControllerStyleActionSheet];

/*
typedef NS_ENUM(NSInteger, UIAlertActionStyle) {
UIAlertActionStyleDefault = 0,
UIAlertActionStyleCancel, 取消按钮
UIAlertActionStyleDestructive 破坏性按钮,比如:“删除”,字体颜色是红色的
} NS_ENUM_AVAILABLE_IOS(8_0);

*/
// 创建action,这里action1只是方便编写,以后再编程的过程中还是以命名规范为主
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"标题1" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了按钮1,进入按钮1的事件");
}];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了取消");
}];
UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

//跳到创建alertview的方法,一般在点击删除这里按钮之后,都需要一个提示框,提醒用户是否真的删除
[self creatAlertController_alert];
}];

//把action添加到actionSheet里
[actionSheet addAction:action1];
[actionSheet addAction:action2];
[actionSheet addAction:action3];

//相当于之前的[actionSheet show];
[self presentViewController:actionSheet animated:YES completion:nil];
}

//创建一个alertview
-(void)creatAlertController_alert {
//跟上面的流程差不多,记得要把preferredStyle换成UIAlertControllerStyleAlert
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"标题" message:@"注释信息,没有就写nil" preferredStyle:UIAlertControllerStyleAlert];

//可以给alertview中添加一个输入框
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"alert中的文本";
}];

UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"标题1" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了按钮1,进入按钮1的事件");
//textFields是一个数组,获取所输入的字符串
NSLog(@"%@",alert.textFields.lastObject.text);
}];
UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了取消");
}];

[alert addAction:action1];
[alert addAction:action2];

[self presentViewController:alert animated:YES completion:nil];
}


效果图如下:

iOS_UIAlertController的使用方法iOS_UIAlertController的使用方法