UIAlertController 取代了 UIAlertView 和 UIActionSheet
声明:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"标题" message:@"这个是UIAlertController的标题" preferredStyle:UIAlertControllerStyleAlert];
/*
typedef NS_ENUM(NSInteger, UIAlertControllerStyle) {
UIAlertControllerStyleActionSheet = 0,
UIAlertControllerStyleAlert
}
*/
添加项目:
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
UIAlertAction *resetAction = [UIAlertAction actionWithTitle:@"重置" style:UIAlertActionStyleDestructive handler:nil];
/*
typedef NS_ENUM(NSInteger, UIAlertActionStyle) {
UIAlertActionStyleDefault = 0,
UIAlertActionStyleCancel,
UIAlertActionStyleDestructive
}
*/
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[alertController addAction:resetAction];
//各个项目的顺序取决于类型,同类型的取决于添加顺序
展示:
[self presentViewController:alertController animated:YES completion:nil];
含对话框的
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
textField.placeholder = @"登录";
//添加监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"密码";
textField.secureTextEntry = YES;
}];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *alertAction){
//移除监听
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}];
okAction.enabled = NO;//设置不可点击
监听方法
- (void)alertTextFieldDidChange:(NSNotification *)notification{
UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
if (alertController) {
UITextField *login = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = login.text.length > 2;
}
}
设置颜色
[cancelAction setValue:[UIColor orangeColor] forKey:@"_titleTextColor"];