【问题标题】:How do i use the text in TextField in a block inside UIAlertController?如何在 UIAlertController 内的块中使用 TextField 中的文本?
【发布时间】:2016-02-13 18:10:05
【问题描述】:

我有一个 UIAlertController,它包含一个文本字段和 2 个按钮:确定和取消。我想检索用户在按下 OK 时在文本字段中输入的文本,但由于文本字段位于块中,我无法从 OK 按钮块访问块内的 textField.text 字段。我如何访问它并使用用户输入的文本?请参阅下面的代码。

    - (IBAction)saveItinerary:(id)sender
{
    NSString *itineraryNameInput = [[NSString alloc] init];
    UIAlertController * alert=   [UIAlertController
                                  alertControllerWithTitle:@"Save Itinerary"
                                  message:@"Enter Name for the Itinerary"
                                  preferredStyle:UIAlertControllerStyleAlert];

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

    }];

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

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

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

    NSLog(@"name = %@", itineraryNameInput);

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

【问题讨论】:

  • 您是否尝试设置实例变量(例如强属性)并将其设置为指向文本字段? @property (strong, nonatomic) UITextField *myAlertTextField; 在您的视图控制器中,然后 self.myAlertTextField = textField; 在块内?

标签: ios objective-c iphone xcode uialertcontroller


【解决方案1】:

使用UIAlertControllertextFields 属性。

UITextField *textField = alert.textFields.firstObject;

【讨论】:

  • 嗨,首先谢谢你!其次,我在 OK 按钮块中尝试了这个,如下所示: UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) { UITextField *textFromUser = alert.textFields.firstObject; textFromUser.text = 行程名称输入; NSLog(@"name = %@", itineraryNameInput); }];但是当我 NSLog var 它不显示任何东西。有什么想法吗?
  • 试试itineraryNameInput = textFromUser.text; 而不是textFromUser.text = itineraryNameInput;
  • 我将 itineraryNameInput 设置为一个属性,并切换了 textfield.text 和 self.itinerartNameInput 的位置,它就像一个魅力!非常感谢@paulvs!
猜你喜欢
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 2014-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多