Making UITextField in next cell first responder

I'm writing an app with a fixed size table (in a ViewController not a TableViewController) and a couple of UITextFields in each cell. The user needs to input data in the textfields and I want to automatically jump to the next textfield once editing of the current textfield stops.

I have the following code in the TableViewCell class which works fine to jump to the next field within the cell but doesn't jump to the next cell.


func textFieldDidEndEditing(_ textField: UITextField) {
  // Try to find next responder
  if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
  nextField.becomeFirstResponder()
  } else {
  textField.resignFirstResponder()
  }
  return
}


I realise that's because after the second edit the next textfield is not in the same cell but I don't know how to address the textfield in the next cell to make it the FirstResponder. I have an observer on the textfield in the cell to check for changes and to update the array holding the table data:

@IBAction func updatePs(_ sender: Any) { psChanged?(ps.text ?? "0") }

where this is in the UITableView cellForRowAt function:

cell.psChanged = { value in self.psP[indexPath.row] = Int(value) ?? 0 }

I though to use this observer to change the FirstResponder from the UITableView cellForRowAt function but I don't know how to.


P.S. I know that working with tags in tables can be problematic but the table is fixed size and rows cannot be deleted.

Replies

You could try this:

- when getting to the last textField in a cell, get the next cell UITableViewCell with

func cellForRow(at: IndexPath)

- then make its first textField the firstResponder.

You need a pointer to the textfileds in the UITable. You created those textFields and placed them into the UITable using the return in the delegate's method cellForRow:atIndexPath: When you do that, you can store a pointer to that UITextField in a Mutable Array - perhaps with the index in the array corresponding to the index path.