2
votes

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];
}
3
«a lot has been cut out that deals with calculations and log etc. I only added the stuff that pertains to this issue.» Can I get an AMEN!jscs
I wouldn't be surprised if it's a different text field after the table view reloads. Try getting the reference again via [[_tableView cellForRowAtIndexPath:destinationIndexPath] viewWithTag:newTag]; immediately after reloadData, and see if it's still the same object as _nextTextFieldSelection.jscs
This makes sense, I'll try it and see.JMD
Your solution worked Josh, although I can't choose your answer because you made it as a comment.JMD
Eh, I've got enough rep as it is. Glad I could help.jscs

3 Answers

1
votes

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.

1
votes

Another solution - to use tableView.insertRows(at: indexPaths, with: .automatic)

0
votes

I was facing same issue - losing focus after tableview reloadData. But adding, cellForRowAtIndexPath after tableview reloadData method solved it. This answer is already given in comments but thought to add here to get more visibility.