Я хочу реализовать функцию смены пароля, это требует, чтобы пользователь вводил свой предыдущий пароль, и я создаю его в диалоговом окне оповещения, я хочу нажать кнопку "Подтвердить изменение", а затем перейти к другому контроллеру представления для изменение пароля. Я написал код, но я не знаю, как писать в следующий момент.
Как добавить textField в UIAlertController?
Ответ 1
Вы можете добавить несколько textFields
в контроллер предупреждений и получать к ним доступ с textFields
свойства textFields
контроллера textFields
Если новый пароль - пустая строка, представьте предупреждение снова. Другой способ - отключить кнопку "Подтвердить", включив ее только тогда, когда в текстовом поле есть текст.
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];
}
}];
Ответ 2
Вы получите все добавленные textFields
из контроллера предупреждений по textFields
readonly, вы можете использовать его для получения текста. подобно
Свифт 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)
Примечание: textField.text не является обязательным, разверните его перед использованием
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];
Посредством [[alertController textFields][0] text]
этой строки, он будет принимать первое текстовое поле, добавленное к alertController, и получит его текст.
Ответ 3
Вот обновленный ответ для Swift 4.0, который создает желаемый вид текстового поля:
// Create a standard UIAlertController
let alertController = UIAlertController(title: "Password Entry", message: "", preferredStyle: .alert)
// Add a textField to your controller, with a placeholder value & secure entry enabled
alertController.addTextField { textField in
textField.placeholder = "Enter password"
textField.isSecureTextEntry = true
textField.textAlignment = .center
}
// A cancel action
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Canelled")
}
// This action handles your confirmation action
let confirmAction = UIAlertAction(title: "OK", style: .default) { _ in
print("Current password value: \(alertController.textFields?.first?.text ?? "None")")
}
// Add the actions, the order here does not matter
alertController.addAction(cancelAction)
alertController.addAction(confirmAction)
// Present to user
present(alertController, animated: true, completion: nil)
И как это выглядит при первом представлении:
И пока принимаю текст:
Ответ 4
UIAlertController *alertVC=[UIAlertController alertControllerWithTitle:@"Login" message:msg preferredStyle:UIAlertControllerStyleAlert];
[alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
{
[email protected]"UserName";
textField.textColor=[UIColor redColor];
textField.clearButtonMode=UITextFieldViewModeWhileEditing;
}
}];
[alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
[email protected]"Password";
textField.textColor=[UIColor redColor];
textField.clearButtonMode=UITextFieldViewModeWhileEditing;
textField.secureTextEntry=true;
}];
UIAlertAction *action=[UIAlertAction actionWithTitle:@"Login" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"Login Tapped");
NSString *username=alertVC.textFields[0].text;
NSString *password=alertVC.textFields[1].text;
NSLog(@"%@ %@",username,password);
}];
[alertVC addAction:action];
[self presentViewController:alertVC animated:true completion:nil];