Search code examples
iosobjective-cuitextfielduialertcontroller

How to add textField in UIAlertController?


I want to realize a function about changing password. It requires users to input their previous password in an alert dialog.

I want to click the button "Confirm the modification" then jump to the other view controller for changing password. I have written some code, but I don't know how to write in the next moment.

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Change password" message:@"Please input your previous password" preferredStyle:UIAlertControllerStyleAlert];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    textField.placeholder = @"please input your previous password";
    textField.secureTextEntry = YES;
}];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handlers:nil];

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Confirm the modification" style:UIAlertActionStyleDestructive handler:*(UIAlertAction *alertAction) {
    if (condition) {
        statements
    }
}];

[alertController addAction:cancelAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];

enter image description here


Solution

  • You can add multiple textfields to alert controller and access them with the alert controller's textFields property

    If the new password is an empty string, present the alert again. Or another way would be to disable the "Confirm" button, enabling it only when text field has text.

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"confirm the modification" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UITextField *password = alertController.textFields.firstObject;
        if (![password.text isEqualToString:@""]) {
    
            //change password
    
        }
        else{
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }];