cocoa-touch – 在屏幕上滚动时重新选择UITableViewCell

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

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

- (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];
}

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

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

解决方法

我花了一个时间来要求自己解决这个问题:

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

以上是来客网为你收集整理的cocoa-touch – 在屏幕上滚动时重新选择UITableViewCell全部内容,希望文章能够帮你解决cocoa-touch – 在屏幕上滚动时重新选择UITableViewCell所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。