gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:43:21 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com