Подтвердить что ты не робот

О UIAlertView с текстовым полем...

У меня есть этот код для запроса UIAlertView с помощью Textfield:

UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"New List Item", @"new_list_dialog")
                                                      message:@"this gets covered" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
UITextField *myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
[myTextField setBackgroundColor:[UIColor whiteColor]];
[myAlertView addSubview:myTextField];
[myAlertView show];
[myAlertView release];

Но я хотел бы добавить значение текстового поля после того, как пользователь нажмет "ОК", и после того, как пользователь щелкнет, я хочу вызвать метод, как я могу назначить его в myAlertView? Спасибо.

4b9b3361

Ответ 1

Объявите текстовое поле как global.And в методе alertView нажмите - (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex, просто возьмите значение текстового поля и выполните необходимые операции с ним.

Сохраняет пересмотренный код

UITextField *myTextField;
...
{

UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"New List Item", @"new_list_dialog")
                                                      message:@"this gets covered" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
[myTextField setBackgroundColor:[UIColor whiteColor]];
[myAlertView addSubview:myTextField];
[myAlertView show];
[myAlertView release];
}
....
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"string entered=%@",myTextField.text);
}

Для iOS 5 и более поздних версий Вы можете использовать свойство alertViewStyle UIAlertView.

Пожалуйста, обратитесь к Hamed Answer для того же

Ответ 2

Если вы хотите добавить TextField в UIAlertView, вы можете использовать это свойство (alertViewStyle) для UIAlertView:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
                                                message:@"Message"
                                               delegate:self
                                      cancelButtonTitle:@"Done"
                                      otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
[alert release];

и в .h файле его добавить UIAlertViewDelegate в качестве протокола и реализовать метод alertView: clickedButtonAtIndex делегировать в файле .m:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%@", [alertView textFieldAtIndex:0].text);
}

Надеюсь, это сработает для вас!

Примечание. "Доступно в iOS 5.0 и более поздних версиях"

Ответ 3

Начиная с iOS 8 UIAlertView устарел в пользу UIAlertController, в котором добавлена ​​поддержка добавления UITextField s.

Swift

let alert = UIAlertController(title: "Title",
                              message: nil,
                              preferredStyle: .alert)
alert.addTextField { (textField) in
    // optionally configure the text field
    textField.keyboardType = .alphabet
}

let okAction = UIAlertAction(title: "OK", style: .default) { [unowned alert] (action) in
    if let textField = alert.textFields?.first {
        print(textField.text ?? "Nothing entered")
    }
}
alert.addAction(okAction)

self.present(alert, animated: true, completion: nil)

Objective-C

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title"
                                                               message:nil
                                                        preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    // optionally configure the text field
    textField.keyboardType = UIKeyboardTypeAlphabet;
}];

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK"
                                                   style:UIAlertActionStyleDefault
                                                 handler:^(UIAlertAction *action) {
                                                         UITextField *textField = [alert.textFields firstObject];
                                                 }];
[alert addAction:okAction];

[self presentViewController:alert animated:YES completion:nil];

Ответ 4

UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Login" message:nil delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
alert.alertViewStyle=UIAlertViewStylePlainTextInput;
[alert show];

Ответ 5

Вам нужна глобальная переменная для поля UIText, вы хотите получить значение в методе делегата AlertView. Я создал сообщение в своем блоге на тему "Как добавить UITextField в UIAlertView из XIB". Вы можете посмотреть следующую ссылку.

http://creiapp.blogspot.com/2011/08/how-to-add-uitextfield-to-uialertview.html

Ответ 6

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hey Welcome"

message:@"MSG" 

delegate:self

cancelButtonTitle:@"Ok Ji" 

otherButtonTitles:nil];

UITextField textField = [[UITextField alloc] initWithFrame:CGRectMake(15.0, 70.0, 200.0, 25.0)];

[textField setBackgroundColor:[UIColor whiteColor]];
[alert addSubview:textField];

[alert show];
[alert release];