Explorer
Explorer

Reputation: 75

How to resign first responder if UITextField is programmatically created inside a UITableViewCell?

I’ve created a custom tableViewCell that contain just a textField for data entry, like in a form. How would I both move to the next cell/textField in the form when the user taps Done and ultimately resign the keyboard when the form is done?

update of problem:

I've created a separate file with the class for my custom tableViewCell. That cell contain just a textfield that's constrained to fit the whole cell. My current solution is to assign each cell as a textField delegate and resign first responder on each cell.

On my tableViewController, I'm dequeuing said custom cell 4 times for the simple form. But I'm not sure how to access the textField in the tableViewCell file for things like jumping to the next textField when the user taps Done or checking that all fields have valid entry to save the information.

Upvotes: 2

Views: 1663

Answers (2)

TheTravloper
TheTravloper

Reputation: 246

I also faced same problem. So to encounter this i selected the option in Attribute Inspecter of tableView - Keyboard > Dismiss on Drag

(This will resign the textfield when you scroll the table view)

OR

You can use the tap gesture on table view/tableview cells to resign responder.

Upvotes: 3

Paul Abrudan
Paul Abrudan

Reputation: 68

A very short version of how I would approach what you're trying to do is:

  1. Store an array of the UITextField currently displayed in the cells.
  2. Append a text field to the array in func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
  3. Remove a text field in func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath)
  4. Keep a reference to the UITextField the user interacts with (via UITextFieldDelegate)
  5. Whenever the user pressed 'Done' call resignFirstResponder() on the UITextField set at step 4
  6. Search for the index of the dismissed text field in the array of visible UITextField.
  7. Increment the index and call beginFirstResponder() on the UITextField at this index.

Upvotes: 0

Related Questions