David Lara
David Lara

Reputation: 51

textFieldDidEndEditing not called in a tableview inside a navigation controller

I have a tableview controller inside a navigation controller. This table simply shows one textfield in each row. In my navigation controller I have a “Done” navigation item that gets all the values entered in the textfields and shows the next screen.

The tableview controller implements UITextFieldDelegte and textFieldDidEndEditing to store the values of every textfield in its datasource (array of strings). In cellForRowAtIndexPath I also assign the delegate of the text fields to themselves. This all works well if I tap on the different textfields, I see how the datasource is properly updated.

My problem is when I do this sequence: type a value in one text field and then tap on the “Done” navigation item. I see that textFieldDidEndEditing is not called so the value is not stored. I also tried with textFieldShouldReturn and textFieldShouldReturn but nothing.

I have read many similar posts and I think the problem is that the "event" is being caught by prepareForSegue instead of textFieldDidEndEditing. If this is correct, I don’t know how to deal with this since I don’t know how to identify the indexPath of that “last edited textfield” when the Done is tapped.

Another related question: I have seen two approaches to get the indexPath of the cell containing the textfield when textFieldDidEndEditing is called:

1) textField.convertPoint + tableView.indexPathForRowAtPoint

2) tableView.indexPathForCell + textField.superview

Both seem to work well without differences (except for the issue that I just stated). Is any approach better than another?

Many thanks in advance for your help!!!

PS: if possible, in Swift code, please!

Upvotes: 0

Views: 1400

Answers (2)

Abhinav
Abhinav

Reputation: 38162

This is how you can address this:

Step 1 : Keep track of your active text field. You can keep a strong reference to it and set it whenever a textField is activated. Something like this:

self.inputField = iCell.inputField;

Step 2 : Once your Done button is tapped, add below line in action handler.

[self.inputField endEditing:YES];

PS: Alternatively, you can simply call [self.view endEditing:YES]; without the need to track the current active text field. I, personally, go with keeping reference to textfield as it helps me doing other stuff around current active textfield.

Upvotes: 0

KavyaKavita
KavyaKavita

Reputation: 1579

On click of done button you can add this line, [self.view endEditing:YES]; This line will resign your currently active text field, and will call your text field delegates.

If you are displaying all text fields within same table section in that case you can assign indexPath.row to textField.tag, and using that tag you can create indexPath.

Upvotes: 6

Related Questions