【问题标题】:How to get the input text from the TextField in an alert [duplicate]如何从警报中的 TextField 获取输入文本 [重复]
【发布时间】:2016-01-06 19:42:39
【问题描述】:

这个问题之前有人问过,在: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];

【问题讨论】:

  • 这应该不难翻译。到目前为止,您拥有 Objective-C 代码的哪一部分?您是否已经创建了UIAlertController?您添加了文本字段吗?
  • 我已经添加了一个文本字段。遇到问题://3。从文本字段中获取值,并在用户单击确定时打印它。 alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in let textField = alert.textFields![0] as UITextField println("Text field: (textField.text) ") }))
  • 好的,请出示您已经获得的代码以及您认为需要帮助的地方,如果您出示您当前的代码,我们很乐意提供一些。

标签: ios objective-c uialertcontroller


【解决方案1】:

您需要使用与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”

【讨论】:

  • 成功了!谢谢! :D
猜你喜欢
  • 2014-12-21
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
相关资源
最近更新 更多