Taking Text From a UIAlertView

北城余情 提交于 2019-12-01 22:03:07

Present alert somewhere in you code and set the view controller from it was presented as the delegate for your UIAlertView.Then implement the delegate to receive the event.

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

Implement the delegate method

- (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] returns immediately, before the user could have entered any text in the text field. You need to get the text after the alert has been dismissed by setting its delegate and implementing alertView:clickedButtonAtIndex: (for example, there are a couple of other possibilities).

In iOS 8 UIAlertview has been deprecated. UIAlertController is used instead of that.

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];

You'll need to wait for the delegate callback alertView:clickedButtonAtIndex to get the text - keep a reference to your text field and show the alert, setting its delegate to self. When that method is called, the user has pressed the button to say they are finished entering text, so it's probably now safe to grab the text out of the text field.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!