objective-c - indexPathForSelectedRow 总是返回 0,0 而不管选择的行

标签 objective-c ios uitableview

我想替换被自定义单元格触及的单元格。我通过调用 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
}

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

最佳答案

您调用 reloadRowsAtIndexPaths: 将导致 TableView 重新加载给定的单元格,从而导致表在该位置不再有选定的行。 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];
}

关于objective-c - indexPathForSelectedRow 总是返回 0,0 而不管选择的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8438030/

相关文章:

ios - 如何将 plist 填充到 UITableView - ios

ios - 如何制作我自己的 UIPickerView?

ios - 创建一个格式数组[][@"string"];

java - com.badlogic.gdx.utils.GdxRuntimeException : Couldn't load file: - Error

ios - 如何进行UITest UIProgressView?

ios - 将缓冲区附加到 AVAssetWriterInputPixelBufferAdaptor *不* 按时间顺序排列?

iPhone空表消息(例如模拟器中的 "No contacts",或搜索中的 "No results")

ios - 当应用程序面向横向和纵向时更改不同的 self.view.backgroundColor 图像

ios - 如何隐藏 YTPlayerView Youtube Logo

objective-c - 如何使用 ABPeoplePickerNavigationController 选择地址簿中的多个条目