iOS表格视图单元格突出显示边框错误



我用以下函数突出显示我的表格单元格边界:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(currentIndexPath != indexPath){
        [self clearCellRowBorder];
        CGColorRef cyan = [UIColor colorWithRed: 0.0f/255.0f green: 255.0f/255.0f blue: 255.0f/255.0f alpha:1.0f].CGColor;
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell.contentView.layer setBorderColor: cyan];
        [cell.contentView.layer setBorderWidth:2.0f];
        currentIndexPath = indexPath;
    }
}

比方说,我有很多行,超过了屏幕大小,所以我需要滚动到底看下一行。我遇到的问题是,当我选择第一行时,第一行会高亮显示,一切都可以,但当我滚动到底部查看其他看不见的行时,其中一行也会高亮显示。有人能帮我解决这个问题吗?

Neo,

由于您已经在currentIndexPath中保存了选定的索引路径,

你可以,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 //after creating cell :)
 if(currentIndexPath != indexPath){
    [self clearCellRowBorder];
   }
 else {
     CGColorRef cyan = [UIColor colorWithRed: 0.0f/255.0f green: 255.0f/255.0f blue: 255.0f/255.0f alpha:1.0f].CGColor;
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell.contentView.layer setBorderColor: cyan];
    [cell.contentView.layer setBorderWidth:2.0f];
 }
}

这应该做你的工作:)快乐的编码:)

为了提高性能,表视图单元格被"重用"。因此,您看到的高亮显示的单元格是正在重复使用的同一单元格。

要解决此问题,可以覆盖UITableViewCell方法prepareForRese,并将突出显示的设置回false(NO)。

编辑示例:

- (void)prepareForReuse {
    [cell.contentView.layer setBorderWidth:0.0f];
}

最新更新