Как запросить у пользователя ввод текста в режиме оповещения - PullRequest
25 голосов
/ 10 августа 2011

Я пишу фрагмент кода, где было бы лучше, если бы я мог использовать всплывающее окно, например UIAlertView, и предлагать пользователю ввести текст, например, пароль.Любые указатели на элегантный способ сделать это?

Ответы [ 6 ]

117 голосов
/ 19 апреля 2012

В iOS 5 все намного проще, просто установите для свойства alertViewStyle соответствующий стиль (UIAlertViewStyleSecureTextInput, UIAlertViewStylePlainTextInput или UIAlertViewStyleLoginAndPasswordInput). Пример:

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Password" message:@"Enter your password:" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
alertView.alertViewStyle = UIAlertViewStyleSecureTextInput;
UITextField *passwordTextField = [alertView textFieldAtIndex:0];
[alertView show];
28 голосов
/ 05 июня 2012

enter image description here> Простой Вы можете подать заявку вот так

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Filename" message:@"Enter the file name:" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField *passwordTextField = [alertView textFieldAtIndex:0];
[alertView show]
16 голосов
/ 10 августа 2011

Лучший способ, который я нашел, это следовать этому руководству: http://junecloud.com/journal/code/displaying-a-password-or-text-entry-prompt-on-the-iphone.html

enter image description here

Код, используемый для достижения этой цели (взят непосредственно из этогоотличный учебник):

UIAlertView *passwordAlert = [[UIAlertView alloc] initWithTitle:@"Server Password" message:@"\n\n\n"
delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel",nil) otherButtonTitles:NSLocalizedString(@"OK",nil), nil];

UILabel *passwordLabel = [[UILabel alloc] initWithFrame:CGRectMake(12,40,260,25)];
passwordLabel.font = [UIFont systemFontOfSize:16];
passwordLabel.textColor = [UIColor whiteColor];
passwordLabel.backgroundColor = [UIColor clearColor];
passwordLabel.shadowColor = [UIColor blackColor];
passwordLabel.shadowOffset = CGSizeMake(0,-1);
passwordLabel.textAlignment = UITextAlignmentCenter;
passwordLabel.text = @"Account Name";
[passwordAlert addSubview:passwordLabel];

UIImageView *passwordImage = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"passwordfield" ofType:@"png"]]];
passwordImage.frame = CGRectMake(11,79,262,31);
[passwordAlert addSubview:passwordImage];

UITextField *passwordField = [[UITextField alloc] initWithFrame:CGRectMake(16,83,252,25)];
passwordField.font = [UIFont systemFontOfSize:18];
passwordField.backgroundColor = [UIColor whiteColor];
passwordField.secureTextEntry = YES;
passwordField.keyboardAppearance = UIKeyboardAppearanceAlert;
passwordField.delegate = self;
[passwordField becomeFirstResponder];
[passwordAlert addSubview:passwordField];

[passwordAlert setTransform:CGAffineTransformMakeTranslation(0,109)];
[passwordAlert show];
[passwordAlert release];
[passwordField release];
[passwordImage release];
[passwordLabel release];
6 голосов
/ 10 августа 2011

Если бы мое приложение еще не было выпущено в течение месяцев или двух, я бы зашел на http://developer.apple.com,, посмотрел на область бета-версии iOS 5 и увидел, может ли UIAlertView что-то подготовить для нас .

3 голосов
/ 13 января 2012

Я думаю, что было бы полезно знать, что UIAlertView не является модальным, поэтому предупреждение не будет блокироваться.

Я столкнулся с этой проблемой, когда хотел запросить у пользователя ввод данных, затем продолжить и затем использовать этот ввод в коде. Но вместо этого код после [alert alert] будет запускаться первым до тех пор, пока вы не достигнете конца цикла выполнения, тогда будет отображаться предупреждение.

1 голос
/ 01 марта 2012

Оптимизированный код:

UIAlertView *passwordAlert = [[UIAlertView alloc] initWithTitle:@"Password"
                                                        message:@"Please enter the password:\n\n\n"
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"Cancel",nil)
                                              otherButtonTitles:NSLocalizedString(@"OK",nil), nil];

UITextField *passwordField = [[UITextField alloc] initWithFrame:CGRectMake(16,83,252,25)];
passwordField.borderStyle = UITextBorderStyleRoundedRect;
passwordField.secureTextEntry = YES;
passwordField.keyboardAppearance = UIKeyboardAppearanceAlert;
passwordField.delegate = self;
[passwordField becomeFirstResponder];
[passwordAlert addSubview:passwordField];

[passwordAlert show];
[passwordAlert release];
[passwordField release];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...