1.创建
UIAlertController *alert =[UIAlertController alertControllerWithTitle: @“警告" message:@"出错了!" preferredStyle:
UIAlertControllerStyleAlert];
2.添加textField
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField){
// 设置TextField的属性
textField.placeholder = @"倪灏";
// 实时监控textField的内容
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(changeAlertValue:) name:
UITextFieldTextDidChangeNotificationobject:textField];
}];
3. 添加按钮
// 创建按钮
UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 点击获取textField里的内容
UITextField *textField = [alert.textFields firstObject];
NSLog(@"textField :%@",textField.text);
}];
// 添加按钮
[alert addAction:action];
// 设置按钮不可点击
action.enabled = NO;
// 显示AlertController
[self presentViewController:alert animated:YES completion:^{}];
4.实现实时监控TextField内容的方法
- (void)changeAlertValue:(NSNotification *)notification{
// 找到AlertController
UIAlertController *alert = (UIAlertController *) self.presentedViewController;
// 找到TextField
UITextField *textField = [alert.textFields firstObject];
// 找到按钮
UIAlertAction *action = [alert.actions firstObject];
// 长度大于4时设置按钮可点击
action.enabled = textField.text.length > 4;
}