之前的文章里我介绍了使用第三方支持Block的UIAlertView控件。今天测试使用了原生的UIAlertController,发现也非常好用。
这是开发者中心的示例:
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
message:@"This is an alert."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
官方建议不要再使用UIAlertView、UIActionSheet。
UIAlertController的风格枚举里,包含了UIAlertView和UIActionSheet的样式。从上面示例可以看出,它原生支持Block写法,可以使一个Controller里弹出很多Alert的时候,更容易控制程序的逻辑。
另外,可以在控件里添加text fields。
方法
alertControllerWithTitle:message:preferredStyle:
属性
title 标题
message 内容
preferredStyle 风格
添加action
- (void)addAction:(UIAlertAction *)action
添加textfields
- (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler
示例:
UIAlertAction* cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction*action){
}];
UIAlertController*alert =[UIAlertController alertControllerWithTitle:@"提示" message:@"内容" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:cancel];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
textField.placeholder = @"测试文本";
}];
[self presentViewController:alert animated:YES completion:nil];
常量定义
UIAlertControllerStyle
typedef enum UIAlertControllerStyle: NSInteger {
UIAlertControllerStyleActionSheet = 0,
UIAlertControllerStyleAlert
} UIAlertControllerStyle;