Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tableView:indexPathForCell returns nil

I am using the method tableView:indexPathForCell to implement a custom delegate that can dynamically resize a UITableViewCell based on the frame size of the UIWebView that is inside of it. The problem is that tableView:indexPathForCell is returning nil when I try to find out what the indexPath of a particular cell is:

- (void)trialSummaryTableViewCell:(TrialSummaryTableViewCell *)cell shouldAssignHeight:(CGFloat)newHeight {
    NSIndexPath *indexPath = [tableV indexPathForCell:cell];
    NSLog(@"tableV: %@\ncell: %@\nindexPath: %@", tableV, cell, indexPath); //<-- 
    // ...
}

Here, tableV does not return nil, cell does not return nil, but indexPath returns nil.

What am I doing wrong?

Edit: I am calling -(void)trialSummaryTableViewCell from the tableView:cellForRowAtIndexPath: method

like image 565
tacos_tacos_tacos Avatar asked Aug 03 '11 16:08

tacos_tacos_tacos


3 Answers

It could be that the cell is not visible at this moment. tableView:indexPathForCell returns nil in this situation. I solved this using indexPathForRowAtPoint this method works even if the cell is not visible. The code:

UITableViewCell *cell = textField.superview.superview;
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cell.center];
like image 139
Jorge Perez Avatar answered Nov 04 '22 14:11

Jorge Perez


[tableV indexPathForCell:cell] returns nil if cell is not visible.

Also if you are calling "trialSummaryTableViewCell" from the "cellForRowAtIndexPath" method, you could easily pass indexPath also to the "trialSummaryTableViewCell" method.

like image 39
Nandakumar R Avatar answered Nov 04 '22 13:11

Nandakumar R


A small update, since Jorge Perez' answer will fail starting at iOS7 (since a UIScrollView has been inserted and calling textField.superview.superview won't work anymore).

You can retrieve the NSIndexPath like this:

//find the UITableViewCell superview
UIView *cell = textField;
while (cell && ![cell isKindOfClass:[UITableViewCell class]])
    cell = cell.superview;

//use the UITableViewCell superview to get the NSIndexPath
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:cell.center];
like image 5
Daniel Avatar answered Nov 04 '22 15:11

Daniel