2

I am trying to create a table view where the user can edit the textfield on each cell. Each cell also allow the transition to another detail view controller. When the user tap on the cell's textfield, it should allow editing and storing the input text to an array respectively.

The problem is that, how do I check the cell/row selected when the textfield is tapped using Swift? (I am able to check the cell being tapped, but not for the case of the textfield in the cell.)

MrRhoads
  • 143
  • 10

2 Answers2

1

There's a couple ways to do this.

The superview property of your text field will be your UITableViewCell (unless you have it embedded within another view in the middle).

In my own code, I often subclass UITableViewCell (and sometimes even the controls within the cell) to give it a property which indicates which row number we're working with.

Michael Dautermann
  • 86,557
  • 17
  • 155
  • 196
  • How do I access the integer value of the row selected in another class of TableViewCell? Would you mind providing some hint in code? Thank you! – MrRhoads Jun 15 '15 at 05:32
  • You'll want something like `NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];` ([more detail here](http://stackoverflow.com/questions/15711889/how-to-get-uitableviewcell-indexpath-from-the-cell)) – Michael Dautermann Jun 17 '15 at 11:14
1

Each textField has a tag property which can be accessed using textField.tag. If you are using a custom Cell, then under cellForRowAt indexPath add a line of code that assigns a tag to your textfield.

let cell = tableView.dequeueReusableCell(withIdentifier: "<identifier>", for: indexPath) as? <customTableViewCell>
cell?.textField.tag = indexPath.row
//perform other cell operations

Make your TableViewController a UITextFieldDelegate, and under textFieldDidEndEditing access the tag property to know which textField was edited

func textFieldDidEndEditing(_ textField: UITextField) {
        print("textfield tag \(textField.tag)")       
    }