iOS becomeFirstResponder and alertView don’t fit together

I have a bit of a problem with becomesFirstResponder

Data recording on iPhone/iPad is done with the class UITextField. We’ll create two instances field1 and field2 of those and arrange them in a view. The user should not be able to select the input field by tapping but rather the program presents the next input field automatically by means of the method becomeFirstResponder. This method causes the keyboard to be displayed and the input field selected.

2 Eingabefelder
The user enters the data and confirms by pressing “return”. The program now hides the keyboard by means of the method resignFirstResponder.

The data is processed which triggers one or two pop up prompts alert1 and alert2 (class UIAlertView). Then the dialogue either continues with the next input field field2 or stays at field1 repeat the input.

These elements can form the following dialogue sequences:

  • field1 … field2
  • field1 … alert1 … field2
  • field1 … alert1 … field1
  • field1 … alert1 … alert2 … field2

But surprisingly you cannot build the following sequence:

  • field1 … alert1 … alert2 … field1

This is where becomeFirstResponder fails:
When field1 is selected a second time via the method the keyboard won’t be displayed and thus data input is not possible.

Some code for experimentation:

- (void)viewDidLoad
{
  [super viewDidLoad];
  [field1 becomeFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
  [textField resignFirstResponder];
  return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
  [self doAlert:@"Message 1" withTag:1];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
  switch (alertView.tag) {
    case 1:
      [self doAlert:@"Message 2" withTag:2];
      break;
      
    case 2:
      [field1 becomeFirstResponder];
      break;
      
    default:
      break;
  }
}

- (void)doAlert:(NSString *)msg withTag:(NSInteger)tag
{
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Test"
                                                  message:msg
                                                 delegate:self
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles:nil];
  alert.tag = tag;
  [alert show];
}

Solution:
The coordination of alert-responder and field-responder does not function after the second alert. The problem can be avoided with the following trick:

[field1 becomeFirstResponder]

change to

[field1 performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0]

Rather strange.

One Reply to “iOS becomeFirstResponder and alertView don’t fit together”

Leave a Reply

Your email address will not be published.