I would like to run the same code if the button on the alert is pressed, or the return key on the keyboard is pressed.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex works for the OK button on the alert, but I can not find an equivalent for the return key.
I have been experimenting with - (BOOL)textFieldShouldReturn:(UITextField *)alertTextField, to no avail.
A year ago, three people in the comments on this site had the same problem and it was not answered:
How do you get the alertview to respond to a “Return” on the keyboard with the same result as tapping the “OK” button? I can’t seem to find anything for the iOS 5 SDK on Google.
What are all the steps necessary to accomplish this?
Edit:
More specifically:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
[[NSUserDefaults standardUserDefaults] setObject:[alertView textFieldAtIndex:0].text forKey:@"url_preference"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
When the user presses OK, that code is run. What is the similar, simple equivalent for the Return key on the keyboard?
Currently, I am trying this:
- (BOOL)textFieldShouldReturn:(UITextField *)alertTextField {
[alertTextField resignFirstResponder];
NSLog(@"test");
return YES;
}
Which does nothing.
This is the definition of my alert:
-(void) noUrl {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Add a URL" message:@"Change it later in Settings" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Load",nil]; //If you change button name, change it in the other alertView function
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeURL;
alertTextField.returnKeyType = UIReturnKeyGo;
alertTextField.enablesReturnKeyAutomatically = YES;
alertTextField.placeholder = @"http://www.example.com";
[alert show];
return;
}
If code needs to be added in another file, or another place, I would appreciate detailed specifics.
Set
and then implement
Also put
UITextFieldDelegatein your .h file as,As per the current edit in the question, you are missing,
Update:
Based on your comment, make alert as a class level variable as,
Then change this method to,