UITableView indexPathForCell: always returns 0 as indexPath.row

I have a UITableView with custom cells. This custom cell looks like a normal cell with a Detail Left style. But my custom cell has a part label and a text box to allow the user to edit the text. I have a Save button, where I want to save all the data entered by the user. I created a 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 user data, I set the text field delegate to the table view controller (self) and implemented the textFieldDidEndEditing: method. In this method, I request the text field parent view (= cell) and request the index cell of this cell. The problem is that I always get 0 for indexPath.row, no matter which 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 zero. Therefore, if it is equal to zero, I get the standard values ​​0, everything is in order. But now: Why am I getting nil for indexPath?

+6
source share
2 answers

I just found a solution myself. I found the code for the supervisor on stackoverflow, so I just copied it. But that does not work. You need to do two supervisors as follows:

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

Now it works great!

+6
source

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

0
source

Source: https://habr.com/ru/post/927562/


All Articles