How to get UITableViewCell's index from its edited UITextField

Zhao Xiang picture Zhao Xiang · Apr 20, 2011 · Viewed 16.5k times · Source

I'm working on an iPhone based BI project.

I have a UITextField in a UITextViewCell, the UITextFieldDelegate points to my UITableViewController, I haven't done any sub-classing for the UITextViewCell nor the UITextField.

Now after the text field end editing on the delegate

  -(void)textFieldDidEndEditing:(UITextField*)textField

I need to know the row index of the current cell I'm editing, is there any way to get the parent cell of the text field? Or can I set some property to the textfield like 'rowIndex' when I create the cell? I really need this value inorderto save the new text.

Thank you. May the Force be with you.

Answer

nikolovski picture nikolovski · Sep 24, 2013

With the changes in the UITableViewCell class in iOS 7 you have to have a more dynamic way to get to the parent cell. You can get to the UITextField's cell by using the following snippet (which you should put in textFieldDidEndEditing: delegate method)

// Get the cell in which the textfield is embedded
id textFieldSuper = textField;
while (![textFieldSuper isKindOfClass:[UITableViewCell class]]) {
    textFieldSuper = [textFieldSuper superview];
}
// Get that cell's index path
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)textFieldSuper];

The snippet works in both iOS 6 and iOS 7.