在屏幕上滚动时,UITableViewCell会被重新选中

Dav*_*rry 8 cocoa-touch uitableview uiscrollview ios

UITableView在我正在开发的iOS应用程序中实现一个问题时,我遇到了一个问题(iOS SDK 4.2).如果我在表格视图中点击一个单元格,然后滚动视图以使单元格离开屏幕,当它返回到视图时,已重新选择最近选择的单元格.

为了测试这个,我创建了一个新的基于View的应用程序项目,UITableView在Interface Builder中拖出一个,并将视图控制器设置为表视图的数据源和委托,并将以下代码放在视图控制器中:

- (NSInteger)numberOfSectionsInTableView:(UITableView *) tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger) section {
    return 12;
}

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

    UITableViewCell *aCell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (!aCell) {
        aCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID] autorelease];
    }

    aCell.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row +1];

    return aCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *aCell = [tableView cellForRowAtIndexPath:indexPath];
    [aCell setSelected:NO animated:YES];
}
Run Code Online (Sandbox Code Playgroud)

当运行它(在模拟器或设备上)时,如果我要点击任何单元格(例如单元格12),它将被选中并取消选择.在此之后,如果当前选择的表格中没有单元格,如果我滚动视图以便最近选择的单元格(在这种情况下为12)离开屏幕,则当它再次出现时将再次选择它.

这是预期的默认行为UITableView吗?或者我的实现可能有错误?在这种情况下取​​消选择此单元格的最佳方法是什么?

Dav*_*rry 13

我花了很多时间想要自己解决这个问题:

我的问题是使用该UITableViewCell方法setSelected:而不是使用该UITableView方法deselectRowAtIndexPath:.