Enable UIAlertAction of UIAlertController only after input

saintjab picture saintjab · Aug 30, 2015 · Viewed 8.5k times · Source

I am using a UIAlertController to present a dialog with a UITextField and one UIAlertAction button labeled "Ok". How do I disable the button until a number of characters (say 5 characters) are input into the UITextField?

Answer

soulshined picture soulshined · Aug 30, 2015

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;
  }
}