1、創建UIAlertController
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"新建" message:@"" preferredStyle:UIAlertControllerStyleAlert];
2、添加一個輸入框 添加輸入框文字改變監聽
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
textField.placeholder = @"請輸入全稱";
}];
3、在確定和取消按鈕事件中相應的移除監聽
UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
UITextField * wordNameTextField = alertController.textFields.firstObject;//獲取到textField
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}];
okAction.enabled = NO;//此處確定按鈕在輸入框內沒有內容時置灰不可用
[alertController addAction:cancleAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
4、實現監聽方法
- (void)alertTextFieldDidChange:(NSNotification *)notification{
UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
if (alertController) {
UITextField *wordNameTextField = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = ![@"" isEqualToString:wordNameTextField.text];//輸入框有內容時可用
}
}