首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UITableView行选择故障?

UITableView行选择故障?
EN

Stack Overflow用户
提问于 2015-11-30 13:11:09
回答 4查看 182关注 0票数 0

我正在开发一个iOS应用程序,用户可以选择他们最喜欢的景点。我想用UITableView中的一个复选标记来显示这一点。调试时,我发现当用户选择(例如)4个景点并向下滚动时,其他景点也会有一个复选标记。即使用户还没有选择他们。这是一个常见的错误/故障吗?

代码:

代码语言:javascript
复制
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

// Configure the cell...

cell.textLabel.text = items[indexPath.row];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    UITableViewCell *tableCell = [tableView cellForRowAtIndexPath:indexPath];
    BOOL isSelected = (tableCell.accessoryType == UITableViewCellAccessoryCheckmark);

    if (isSelected) {
        tableCell.accessoryType = UITableViewCellAccessoryNone;
    }
    else {
        tableCell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

}

`

下面是一个.gif文件,向您展示在谣言中发生的事情:

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-11-30 13:25:34

代码语言:javascript
复制
@property (nonatomic, strong) NSMutableSet *selectedIndexPaths;

- (void)viewDidLoad {
   ...

    _selectedIndexPaths = [NSMutableSet set];

   ...
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...

    tableCell.accessoryType = ([self.selectedIndexPaths containsObject:indexPath])
        ? UITableViewCellAccessoryCheckmark
        : UITableViewCellAccessoryNone;

    ...
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ...

    UITableView *tableCell = [tableView cellForRowAtIndexPath:indexPath];

    if ([self.selectedIndexPaths containsObject:indexPath]) {
        [self.selectedIndexPaths removeObject:indexPath];
        tableCell.accessoryType = UITableViewCellAccessoryNone;
    } else {
        [self.selectedIndexPaths addObject:indexPath];
        tableCell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

    ...
}
票数 0
EN

Stack Overflow用户

发布于 2015-11-30 13:15:34

这是一个非常常见的bug,但不是iOS错误。:)

问题是单元格被重用,如果您更改了单元格的一个方面,当它再次给您时,它不会自动重置为任何默认设置。

使用的策略是:将“选定”状态保存在用于填充单元格的数据中,然后在cellForRowAtIndexPath中打开或关闭附件。

票数 3
EN

Stack Overflow用户

发布于 2015-11-30 13:14:40

这不是窃听器/故障。应该是这样的。因为您正在使用dequeueReusableCellWithIdentifier。必须在cellForRowAtIndexPath中重置单元格的状态。

对于选定的单元格,应创建一个数组来处理所选单元格的索引。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33999456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档