Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textFieldShouldBeginEditing called multiple times when "Tab" key is pressed

I have a form screen with multiple input fields that are contained inside UITableView. If a user connects bluetooth keyboard then he is able to press "Tab" key. The problem with that is textFieldShouldBeginEditing method is called multiple times for every text field. Is it the normal behaviour? The normal behaviour would be if some field is in focus and the user presses tab then cursor should jump to some other text field and so textFieldShouldBeginEditing would be called only once (for this text field).

It looks like this problem is unsolved (post1, post2). Do you guys ignore the presence of this issue, or have found a fix for that?

like image 264
Centurion Avatar asked Mar 19 '14 11:03

Centurion


1 Answers

I have a UIViewController where I listen to the UITextFieldDelegate textFieldShouldBeginEditing and have a special action on only one of my textfields. So when hitting Tab on a bluetooth keyboard it causes the special case to fire.

Today I've finally found asolution:

I'm registering a keyCommand for the Tab key and then having it use a Category on the UIResponder to find the firstResponder (the current textField) and then firing the return via the delegate method.

You will first need this Category to get the firstResponder: https://stackoverflow.com/a/21330810/747369

Then just register the keyCommand and get the current firstResponder.

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self addKeyCommand:[UIKeyCommand keyCommandWithInput:@"\t" modifierFlags:0 action:@selector(tabKeyPressed:)]];
}

- (void)tabKeyPressed:(UIKeyCommand *)sender
{
    id firstResponder = [UIResponder currentFirstResponder];
    if ([firstResponder isKindOfClass:[UITextField class]])
    {
        UITextField *textField = (UITextField *)firstResponder;
        // Call the delegate method or whatever you need
        [self textFieldShouldReturn:textField];
    }
}
like image 171
Kramer Avatar answered Sep 21 '22 12:09

Kramer