Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the input text from the TextField in an alert [duplicate]

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];
like image 871
Jay Avatar asked Dec 06 '25 03:12

Jay


1 Answers

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'

like image 146
luk2302 Avatar answered Dec 07 '25 20:12

luk2302



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!