UIAlertController作为iOS8新特性,按键的触发方法采用block回调方式实现,一改UIActionSheet和UIAlertView中的delegate模式;
ActionSheet
UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction * aAction = [UIAlertAction actionWithTitle:@"Default" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSLog(@"Default");
}];
UIAlertAction * bAction = [UIAlertAction actionWithTitle:@"Destructive" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
NSLog(@"Destructive");
}];
[alertVC addAction:cancelAction];
[alertVC addAction:aAction];
[alertVC addAction:bAction];
[self presentViewController:alertVC animated:YES completion:nil];
在preferredStyle为ActionSheet模式下,只有添加了UIAlertActionStyleCancel形式的UIAlertAction后,点击背景遮罩才会同时触发该方法并收起弹出窗;
(该特性其实与UIActionSheet是一致的,当cancelButtonTitle设为nil时,点击背景遮罩是无效的)
UIAlertController对象添加UIAlertAction的顺序(Cancle除外)与UIActionSheetDelegate方法中的clickedButtonIndex一致;
Alert
UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction * aAction = [UIAlertAction actionWithTitle:@"Default" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSLog(@"Default");
}];
UIAlertAction * bAction = [UIAlertAction actionWithTitle:@"Destructive" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
NSLog(@"Destructive");
}];
UIAlertAction * cAction = [UIAlertAction actionWithTitle:@"打印文本内容" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSLog(@"%@", [alertVC.textFields firstObject].text);
}];
[alertVC addAction:cancelAction];
[alertVC addAction:aAction];
[alertVC addAction:bAction];
[alertVC addAction:cAction];
[alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.delegate = self;
textField.placeholder = @"请输入帐号";
}];
[self presentViewController:alertVC animated:YES completion:nil];
仅在preferredStyle为Alert模式下,可以在弹出框内添加TextField,我们可以为该输入框添加delegate,并通过UIAlertController的属性textFields数组获取某个textField。
tips:通过
alertVC.view.tintColor = [UIColor orangeColor];
可修改按键文字颜色(对title、message及Destructive按键无效)