显示带文本字段输入的警报

时间:2016-07-21 14:40:29

标签: ios objective-c alert

如何在警报中显示文本输入字段以获取用户的输入并在应用程序中使用该输入(在标签上显示输入)?

如下所示 enter image description here enter image description here

感谢您的时间。

2 个答案:

答案 0 :(得分:15)

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Text"
                                                                message:@"Enter some text below"
                                                         preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *submit = [UIAlertAction actionWithTitle:@"Submit" style:UIAlertActionStyleDefault
                                               handler:^(UIAlertAction * action) {

                                                   if (alert.textFields.count > 0) {

                                                       UITextField *textField = [alert.textFields firstObject];

                                                       textField.text // your text
                                                   }

                                               }];

[alert addAction:submit];

[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    textField.placeholder = @"something"; // if needs
}];

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

答案 1 :(得分:1)

使用UIAlertView

将TextField添加到alertViewStyle设置UIAlertViewStylePlainTextInput属性
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
                                                message:@"Message"
                                               delegate:self
                                      cancelButtonTitle:@"Done"
                                      otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];

在.h文件中添加UIAlertViewDelegate作为协议,并在.m文件中实现委托方法alertView:clickedButtonAtIndex

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