Referencing a textField inside a tableViewCell

I needed to know which textField within a tableViewCell was updated. In the NMR Calculator app, I kept the references of textFields. Now, I have realized that it is not a good way. So I started searching a solution.

First, I found that it is possible to get an indexPath from the point or frame of something. Then, I found this page from Stack Overflow: Get indexPath of UITextField in UITableViewCell with Swift

With a textField, finding the indexPath of the tableViewCell owning the textField can be done this way. First, the tableViewCell is set to be a delegate of the textField, when the method tableView(_:cellForRowAt:) is called. Second, a protocol for the tableViewCell is defined.

protocol SomeTableViewCellDelegate: AnyObject {
  func didEndEditing(_ cell: SomeTableViewCell)

class SomeTableViewCell: UITableViewCell {
  @IBOutlet weak var textField: UITextField!

  weak var delegate: SomeTableViewCellDelegate?

  override func awakeFromNib() {
    textField.delegate = self

Now the viewController owning the tableView is set to be a delegate of SomeTableViewCell and conforms to the protocol SomeTableViewCellDelegate.

extension SomeViewController: SomeTableViewCellDelegate {
  func didEndEditing(_ cell: SomeTableViewCell) {
     let indexPath = tableView.indexPath(for: cell)

A delegation of a delegation! I would like to adapt this elegant design pattern in the NMR Calculator app.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s