Search code examples
iosobjective-ccocoa-touch

tableView reloadData loses textfield Focus


I have some cells with textfields and other labels. Basically, after the user inputs data with the keyboard they can navigate to another textfield (through various means) and I save the textField they wish to go to in a pointer, then set the first responder triggering the didEndEditing method of the textfield. In didEndEditing I call a refresh method that reloads the tableData to update various labels, and then I attempt to setFirstResponder again to the textfield I have stored.

The end result is that the keyboard stays on screen, but the textfield doesn't get focus. If however, you try again, it works the second time...

Here is some code. Keep in mind a lot has been cut out that deals with calculations and log etc. I only added the stuff that pertains to this issue.

edit also, I know I mentioned I am using arrow buttons to navigate.. the issue is also here if you dont use the arrow buttons. You have to manually press(or click) a textfield twice to get focus after leaving another.

 //user presses an arrow button to enter textfield

 //logic is done here to find what the next textfield would be

 _nextTextFieldSelection = (UITextField *)[[_tableView cellForRowAtIndexPath:destinationIndexPath] viewWithTag:newTag];
[_nextTextFieldSelection becomeFirstResponder];


- (void)textFieldDidEndEditing:(UITextField *)textField
{
     //some stuff for calculations
     [self refreshScreen]
}

- (void)refreshScreen
{
    [_tableView reloadData]; 
    //set tables values

    [_nextTextFieldSelection becomeFirstResponder];
}

Solution

  • When you reload the table the cells are recreated. your cached nextTextFieldSelection may no longer be a reference to the correct text field instance. Try caching the indexPath instead of the text field and then use your tag to get the appropriate text field from the cell given the index path.