NSExplorer
NSExplorer

Reputation: 12149

indexPathForSelectedRow always returns 0,0 irrespective of the row selected

I would like to replace the cell that is touched by a custom cell. I do this by calling reloadRowsAtIndexPaths

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    NSLog(@"Row selected: %d",  [tableView indexPathForSelectedRow] row]);
    NSLog(@"Section selected: %d",  [tableView indexPathForSelectedRow] section]);

    //return a custom cell for the row selected
}

When I try to access/log the indexPathForSelectedRow from within the cellForRowAtIndexPath, it returns 0,0 no matter which cell I select. Why is this?

Upvotes: 0

Views: 5098

Answers (1)

myuiviews
myuiviews

Reputation: 1261

Your call to reloadRowsAtIndexPaths: will cause the table view to reload the given cells and therefore cause the table to no longer have a selected row at that position. The cellforRowAtIndexPath method is a request from the data source to provide a row for the given index path. If you need to determine if a cell was selected prior to the request, you could store the indexPath of the selected row in a member. Then check the member in your cellForIndexPathMethod.

The following code sample assumes you are using ARC for memory management.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"Cell %d_%d", indexPath.section, indexPath.row];

    // Configure the cell...
    if(selectedIndexPath != nil) {
        NSLog(@"Selected section:%d row:%d", selectedIndexPath.section, selectedIndexPath.row);

        //TODO:Provide a custom cell for the selected one.

        //Set the selectedIndexPath to nil now that it has been handled
        selectedIndexPath = nil;
    }

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Store the selected indexPath
    selectedIndexPath = indexPath;

    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

Upvotes: 5

Related Questions