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?
So to start with the indexPath. row will be 0. Then it will be 1, then 2, then 3 and so on. You do this so that you can get the correct string from the array each time.
A list of indexes that together represent the path to a specific location in a tree of nested arrays.
add an 'indexPath` property to the custom table cell. initialize it in cellForRowAtIndexPath. move the tap handler from the view controller to the cell implementation. use the delegation pattern to notify the view controller about the tap event, passing the index path.
Index paths describe an item's position inside a table view or collection view, storing both its section and its position inside that section. For example, the first row in a table would have section 0, row 0, whereas the eighth row in the fourth section would have section 3, row 7.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With