无论选择哪一行,indexPathForSelectedRow始终返回0,0

NSE*_*rer 0 objective-c uitableview ios

我想替换自定义单元格触摸的单元格.我通过调用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
}
Run Code Online (Sandbox Code Playgroud)

当我尝试从cellForRowAtIndexPath中访问/记录indexPathForSelectedRow时,无论我选择哪个单元格,它都会返回0,0.为什么是这样?

myu*_*ews 5

您对reloadRowsAtIndexPaths的调用将导致表视图重新加载给定的单元格,从而导致表格在该位置不再具有选定的行.所述的cellForRowAtIndexPath方法是从数据源的请求,以提供对于给定的索引路径的行.如果需要确定在请求之前是否选择了单元格,则可以将所选行的indexPath存储在成员中.然后检查cellForIndexPathMethod中的成员.

以下代码示例假定您使用ARC进行内存管理.

- (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];
}
Run Code Online (Sandbox Code Playgroud)