Search code examples
iosobjective-cuitextfielduialertcontroller

Enable UIAlertAction of UIAlertController only after input is validated


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?


Solution

  • 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