如何在警报中从TextField获取输入文本

时间:2016-01-06 19:42:39

标签: ios objective-c uialertcontroller

以前曾在Get input value from TextField in iOS alert in Swift提出过这个问题。但是,是否有人使用Objective-C语言编写代码?

提前致谢!

到目前为止我得到了什么:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Adding A Row"
    message:@"Enter A Number"
    preferredStyle:UIAlertControllerStyleAlert];

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

UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    [alert dismissViewControllerAnimated:YES completion:nil];
}];

UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//Do some action here
}];

[alert addAction:cancel];
[alert addAction:ok];

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

1 个答案:

答案 0 :(得分:5)

您需要使用与Swift中相同的逻辑:在动作处理程序中以下列方式编写alert.textFields[0].text

UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    NSString *input = alert.textFields[0].text;
    NSLog(@"input was '%@'", input);
}];

在我的测试中打印

  

输入是' 1234'