How do I access the input from my text field in UIAlertController with objective c?

Allison picture Allison · Nov 5, 2014 · Viewed 11.6k times · Source

I'm changing everything over from AlertView to AlertController, but I can't find anything online for objective c that retrieves what the user inputs in a text field for the AlertController. Here is what I have:

if ([UIAlertController class]) {
            UIAlertController *alertControllerK2 = [UIAlertController
                                                    alertControllerWithTitle:@"\u00A0"
                                                    message:@"Please enter the first number."
                                                    preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *K2okAction = [UIAlertAction
                                         actionWithTitle:@"OK"
                                         style:UIAlertActionStyleDefault
                                         handler:nil];
            [alertControllerK2 addTextFieldWithConfigurationHandler:^(UITextField *K2TextField)
             {
                 K2TextField.placeholder = NSLocalizedString(@"Please enter the first number.", @"Please enter the first number.");
             }];
            [alertControllerK2 addAction:K2okAction];
            [self presentViewController:alertControllerK2 animated:YES completion:nil];
        } else {
            UIAlertView *alertK2;
            alertK2 = [[UIAlertView alloc]
                       initWithTitle:@"\u00A0"
                       message:@"Please enter the first number."
                       delegate: self
                       cancelButtonTitle:@"OK"
                       otherButtonTitles:nil];
            alertK2.alertViewStyle=UIAlertViewStylePlainTextInput;
            [alertK2 show];
        }

The problem is that K2TextField is defined inside the UIAlertController, so I can't access it outside of that code. But if I try to predefine it, I get an error message. Any help would be greatly appreciated!

Answer

BeccaP picture BeccaP · Nov 6, 2014

The UIAlertController has an array of textFields that are ordered by when you added them (the first one you added is index 0). Since it is a generic array, you will have to cast the result before accessing the text field.

__weak UIAlertController *alertRef = alertController;
UIAlertAction* okAction = [UIAlertAction actionWithTitle:@"Button Text"
                                         handler:^(UIAlertAction * action) {
                                             // access text from text field
                                             NSString *text = ((UITextField *)[alertRef.textFields objectAtIndex:0]).text;
                                         }];