Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get indexPath of UITextField in UITableViewCell with Swift

So, I'm building a Detail View Controller App that presents a Table with a two-part cell: the label and the Text Field.

I'm trying to retrieve the Text Field value and add it to an array. I tried to use the "textField.superview.superview" technique but it didn't worked.

func textFieldDidEndEditing(textField: UITextField!){
    var cell: UITableViewCell = textField.superview.superview
    var table: UITableView = cell.superview.superview
    let textFieldIndexPath = table.indexPathForCell(cell)
}

Xcode fails to build and presents that "UIView is not convertible to UITableViewCell" and "to UITableView". The referring table has two sections, of four and two rows, respectively.

Thanks in advance.

EDIT: added ".superview" at the second line of the function.

like image 842
Nuno Casteleira Avatar asked Jun 06 '14 01:06

Nuno Casteleira


2 Answers

While the currently accepted answer might work, it assumes a specific view hierarchy, which is not a reliable approach since it is prone to change.

To get the indexPath from a UITextField that is inside a cell, it's much better to go with the following:

func textFieldDidEndEditing(textField: UITextField!){
    let pointInTable = textField.convert(textField.bounds.origin, to: self.tableView)
    let textFieldIndexPath = self.tableView.indexPathForRow(at: pointInTable)
    ...
}

This will continue to work independent of eventual changes to the view hierarchy.

like image 87
Cezar Avatar answered Oct 03 '22 00:10

Cezar


You'll want to cast the first and second lines in your function, like this:

func textFieldDidEndEditing(textField: UITextField!){
    var cell: UITableViewCell = textField.superview.superview as UITableViewCell
    var table: UITableView = cell.superview as UITableView
    let textFieldIndexPath = table.indexPathForCell(cell)
}

superview returns a UIView, so you need to cast it to the type of view you expect.

like image 32
Connor Avatar answered Oct 03 '22 00:10

Connor