Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexPathForCell returns nil since ios7

my app was running fine under ios6.1. tried the ios7 simulator and the following part does not work:

EditingCell *cell = (EditingCell*) [[textField superview] superview];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSLog(@"the section is %d and row is %d", indexPath.section, indexPath.row);
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *rowKey = [[keysForRows objectAtIndex: section] objectAtIndex: row];

It always comes:

the section is 0 and row is 0

although another section / row were selected. Has someone an idea why this does not work under ios7?

like image 295
Ludwig Meier Avatar asked Sep 11 '13 13:09

Ludwig Meier


2 Answers

Your approach to find the "enclosing" table view cell of a text field is fragile, because is assumes a fixed view hierarchy (which seems to have changed between iOS 6 and iOS 7).

One possible solution would be to traverse up in the view hierarchy until the table view cell is found:

UIView *view = textField;
while (view != nil && ![view isKindOfClass:[UITableViewCell class]]) {
    view = [view superview];
}
EditingCell *cell = (EditingCell *)view;

A completely different, but often used method is to "tag" the text field with the row number:

cell.textField.tag = indexPath.row;   // in cellForRowAtIndexPath

and then just use that tag in the text field delegate methods.

like image 115
Martin R Avatar answered Oct 24 '22 00:10

Martin R


I was finding cells the same way you were. Now I use this quick method if I have a button in a cell and know the tableview I'm in. It'll return the tableviewcell.

-(UITableViewCell*)GetCellFromTableView:(UITableView*)tableView Sender:(id)sender {
    CGPoint pos = [sender convertPoint:CGPointZero toView:tableView];
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:pos];
    return [tableView cellForRowAtIndexPath:indexPath];
}
like image 20
drexel sharp Avatar answered Oct 24 '22 01:10

drexel sharp