当升级Xcode到7.2版本后突然发现之前一直写的UIAlertView和UIActionSheet官方不推荐使用了,查看了下原来从8.0开始就不赞成使用了,好吧,竟然出现了UIAlertController,那就用人家推荐的呗.貌似还得看下怎么用!
在iOS 8中,UIAlertController在功能上是和UIAlertView以及UIActionSheet相同的,UIAlertController以一种模块化替换的方式来代替这两个控件的功能和作用。是使用对话框(alert)还是使用上拉菜单(action sheet),就取决于在创建控制器时,您是如何设置首选样式的。
割了,废话不多说,写写代码怎么实现;
一.提示框
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"标题" message:@"我勒个去" preferredStyle:UIAlertControllerStyleAlert];
// 通过创建UIAlertAction的实例,可以将动作按钮添加到控制器上。UIAlertAction由标题字符串、样式以及当用户选中该动作时运行的代码块组成。
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDestructive handler:nil];
[alert addAction:cancelAction];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
1.登陆密码样式对话框
UIAlertController * alert1 = [UIAlertController alertControllerWithTitle:@"登陆" message:@"输入正确的账号密码" preferredStyle:UIAlertControllerStyleAlert];
[alert1 addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"登陆";
}];
[alert1 addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"密码";
textField.secureTextEntry = YES;
}];
UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
UITextField * login = alert1.textFields.firstObject;
UITextField * password = alert1.textFields.lastObject;
NSLog(@"login = %@, password = %@",login.text,password.text);
}];
UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert1 addAction:okAction];
[alert1 addAction:cancel];
[self presentViewController:alert1 animated:YES completion:nil];
二.上拉菜单
UIAlertController * sheet = [UIAlertController alertControllerWithTitle:@"标题" message:@"我勒个去" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction * deleteAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:nil];
UIAlertAction * archiveAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"保存了"); //改成了block,添加点击事件;
}];
// 如果上拉菜单中有“取消”按钮的话,那么它永远都会出现在菜单的底部,不管添加的次序是如何。其他的按钮将会按照添加的次序从上往下依次显示。《iOS 用户界面指南》要求所有的“毁坏”样式按钮都必须排名第一(推荐把删除放到第一栏)。Destructive警示(根据苹果官方的定义,“警示”样式的按钮是用在可能会改变或删除数据的操作上。因此用了红色的醒目标识来警示用户。)
[sheet addAction:cancelAction];
[sheet addAction:archiveAction];
[sheet addAction:deleteAction];
[self presentViewController:sheet animated:YES completion:nil];