You will get all added textfields from alert controller by its textFields
readonly property, you can use it to get its text.
Like
Swift 4:
let alertController = UIAlertController(title: "", message: "", preferredStyle: .alert)
alertController.addTextField { textField in
textField.placeholder = "Password"
textField.isSecureTextEntry = true
}
let confirmAction = UIAlertAction(title: "OK", style: .default) { [weak alertController] _ in
guard let alertController = alertController, let textField = alertController.textFields?.first else { return }
print("Current password (String(describing: textField.text))")
//compare the current password and do action here
}
alertController.addAction(confirmAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
Note: textField.text is optional, unwrap it before using
Objective-C:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"Current password";
textField.secureTextEntry = YES;
}];
UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"Current password %@", [[alertController textFields][0] text]);
//compare the current password and do action here
}];
[alertController addAction:confirmAction];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"Canelled");
}];
[alertController addAction:cancelAction];
[self presentViewController:alertController animated:YES completion:nil];
By [[alertController textFields][0] text]
this line, it will take first textfield added to the alerController and get its text.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…