objective-cuibuttonuitextfieldbecomefirstresponder

How to BecomeFirstResponder the UiTextField after each UiButton's Enter action in Objective-C


I have UITextField & UIButton. I want to becomeFirstResponder my TextField after each Enter action (my Button action) but it doesn't work ! here is my code :

[_textfield becomeFirstResponder];

[_textfield addTarget:self action:@selector(backAction:) 
forControlEvents:UIControlEventEditingDidEndOnExit];

[_back addTarget:self action:@selector(backAction:) 
forControlEvents:UIControlEventTouchUpInside];

- (void)backAction:(id)sender
{
    [users addObject:_textfield.text];
    _textfield.text = nil;
    [_textfield becomeFirstResponder];
}

Solution

  • Instead of "backaction:" add a separate action for textfield.

    [_textfield addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventEditingDidEndOnExit];
    

    And in this targetted method,

    - (void)dismiss {
    [self performSelector:@selector(backAction:) withObject:nil afterDelay:0]}
    

    It seems to be working when I tried.

    On clicking return, editing gets completed and keyboard resigns. But 'backaction:' will get triggered before that and the keyboard will disappear. Hope this helps.