从UIAlertView获取文本

似乎缺少某些东西,但是下面的代码为titletitle1生成了nil值(即使它正确启动了正确的警报类型并且没有指示任何警告或错误)。 这个UIAlertView实现可能有什么问题?

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"High Score" message:(NSString *)scoreMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; alert.alertViewStyle= UIAlertViewStylePlainTextInput; UITextField *title1 = [alert textFieldAtIndex:0]; [alert show]; title1= [alert textFieldAtIndex:0]; NSString *title = title1.text; NSLog(@"The name is %@",title); NSLog(@"Using the Textfield: %@",[[alert textFieldAtIndex:0] text]); 

在代码中的某处显示警报并从中设置视图控制器作为UIAlertView的委托呈现。然后实现委托以接收事件。

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"High Score" message:@"Score Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]; alert.alertViewStyle= UIAlertViewStylePlainTextInput; [alert show]; 

实现委托方法

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ UITextField *textField = [alertView textFieldAtIndex:0]; NSString *title = textField.text; NSLog(@"The name is %@",title); NSLog(@"Using the Textfield: %@",[[alertView textFieldAtIndex:0] text]); } 

[alert show]在用户输入文本字段中的任何文本之前立即返回。 通过设置其delegate并实现alertView:clickedButtonAtIndex:您需要在警报解除获取文本(例如,还有其他几种可能性)。

在iOS 8中,UIAlertview已被弃用。 使用UIAlertController而不是它。

 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Add Fruit" message:@"Type to add a fruit" preferredStyle:UIAlertControllerStyleAlert]; [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){ textField.placeholder = @"Fruit"; }]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { UITextField *textFiel = [alert.textFields firstObject]; [fruits addObject:textFiel.text]; }]; [alert addAction:okAction]; [self presentViewController:alert animated:YES completion:nil]; 

您需要等待委托回调alertView:clickedButtonAtIndex以获取文本 – 保持对文本字段的引用并显示警报,将其delegate设置为self 。 当调用该方法时,用户按下按钮表示他们已完成输入文本,因此现在可以安全地从文本字段中取出文本。