3

This question has been asked before, in:Get input value from TextField in iOS alert in Swift. However, does somebody have the code in the Objective-C language?

Thanks in advance!

What I've gotten so far:

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];
Community
  • 1
  • 1
Jay
  • 49
  • 2
  • 11
  • That should not be too hard to translate. What part of the Objective-C code do you have so far? Have you created an `UIAlertController` already? Have you added a textfield? – luk2302 Jan 06 '16 at 19:44
  • I have already add a textfield. Having trouble with : //3. Grab the value from the text field, and print it when the user clicks OK. alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in let textField = alert.textFields![0] as UITextField println("Text field: \(textField.text)") })) – Jay Jan 06 '16 at 19:46
  • Okay, please show the code that you have already got and where you think you need help, will be happy to provide some if you show the current code of yours. – luk2302 Jan 06 '16 at 19:47

1 Answers1

5

You need to use the same logic as in Swift: write alert.textFields[0].text inside the action handler in the following way:

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

Which in my test prints

input was '1234'

luk2302
  • 55,258
  • 23
  • 97
  • 137