6

I have a UITableView with custom cells in it. This custom cell looks like a normal cell with Style "Detail Left". But my custom cell has a detail label and a text field, to allow the user to edit the text. I have a Save button where I want to save all data the user entered. I made up the custom cell using this tutorial: http://agilewarrior.wordpress.com/2012/05/19/how-to-add-a-custom-uitableviewcell-to-a-xib-file-objective-c/#comment-4883

To get the user data I set the text field's delegate to the table view controller (self) and implemented the textFieldDidEndEditing: method. In this method I ask for the text field's parent view (= cell) and ask for the indexPath of this cell. The problem is, I always get 0 for indexPath.row, no matter what cell I edit. What am I doing wrong?

Here is my code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:[CustomCell reuseIdentifier] forIndexPath:indexPath];
if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    cell = self.customCell;
    self.customCell = nil;
}

cell.label.text = @"Some label text";
cell.editField.delegate = self;
cell.accessoryType = UITableViewCellAccessoryNone;

return cell;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
CustomCell *cell = (CustomCell *) textField.superview;

NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

NSLog(@"the section is %d and row is %d", indexPath.section, indexPath.row);
...
}

EDIT: I just found out, that the returned indexPath is nil. So if it is nil I get the standard values 0, thats okay. But now: Why do I get nil for indexPath?

tester
  • 3,977
  • 5
  • 39
  • 59
  • This is a similar thread saying the reason for that http://stackoverflow.com/questions/6930026/tableviewindexpathforcell-returns-nil – Khaled Annajar Apr 16 '13 at 16:29

2 Answers2

5

I just found the solution myself. I found the code for the superview in stackoverflow, so I just copied it. But that does not work. You need to do two superviews like this:

CustomCell *cell = (CustomCell *) textField.superview.superview;

Now it works fine!

tester
  • 3,977
  • 5
  • 39
  • 59
0

Could you just add an index property to your CustomCell and populate it with indexPath.row inside (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Resh32
  • 6,500
  • 3
  • 32
  • 40
  • Good idea, I did this but I get an error saying "unrecognized selector sent to instance... [UITableViewCellContentView indexPath]" (I called the property indexPath). So, I am a little bit confused about why cell is now a UITableViewCellContentView and not my CustomCell. – tester Oct 12 '12 at 12:26