Enable UIAlertAction of UIAlertController only after input
You can add an observer to your UITextField
:
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
[textField addTarget:self action:@selector(alertControllerTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}
but first disable your button:
okAction.enabled = NO;
Then validate it in the method you specified :
- (void)alertTextFieldDidChange:(UITextField *)sender {
UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
if (alertController) {
UITextField *someTextField = alertController.textFields.firstObject;
UIAlertAction *okAction = alertController.actions.lastObject;
okAction.enabled = someTextField.text.length > 2;
}
}
Add following property in your header file
@property(nonatomic, strong)UIAlertAction *okAction;
then copy the following code in your viewDidLoad
method of your ViewController
self.okAction = [UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:nil];
self.okAction.enabled = NO;
UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil
message:@"Enter your text"
preferredStyle:UIAlertControllerStyleAlert];
[controller addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.delegate = self;
}];
[controller addAction:self.okAction];
[self presentViewController:controller animated:YES completion:nil];
Also implement the following UITextField
delegate method in your Class
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[self.okAction setEnabled:(finalString.length >= 5)];
return YES;
}
This should work
Swift 3 implementation based on soulshined's answer:
var someAlert: UIAlertController {
let alert = UIAlertController(title: "Some Alert", message: nil, preferredStyle: .alert)
alert.addTextField {
$0.placeholder = "Write something"
$0.addTarget(self, action: #selector(self.textFieldTextDidChange(_:)), for: .editingChanged)
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
let submitAction = UIAlertAction(title: "Submit", style: .default) { _ in
// Do something...
}
submitAction.isEnabled = false
alert.addAction(submitAction)
return alert
}
func textFieldTextDidChange(_ textField: UITextField) {
if let alert = presentedViewController as? UIAlertController,
let action = alert.actions.last,
let text = textField.text {
action.isEnabled = text.characters.count > 0
}
}