ios - UITableView cell accessoryView 图片问题

标签 ios xcode uitableview

我正在尝试使用以下代码在我的 UITableViewCells 的特定行上显示“挂锁”图标:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCell"];

    GPBTopic *topic = [self.topics.list objectAtIndex:indexPath.row];
    cell.textLabel.text= topic.name;

    if ((indexPath.row == 5) || (indexPath.row == 9))
    {
            cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:@"lock_icon.png"]];;
            [cell.accessoryView setFrame:CGRectMake(0, 0, 24, 24)];

    }

    return cell;
}

我得到了一个有趣的结果 - 挂锁最初显示在第 5,9 行,但是当我向下和向上滚动列表时,图标也会随机重新显示在其他单元格的 accessoryView 上(顺便说一句,只有 1 个部分),并且滚动变得非常不稳定和滞后......我向上/向下滚动的次数越多,显示的实例就越多! 为什么?这里的错误在哪里?

帮忙,谢谢!

最佳答案

细胞得到重用。您需要每次重置 accessoryView。 这只是一个小改动:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCell"];

    GPBTopic *topic = [self.topics.list objectAtIndex:indexPath.row];
    cell.textLabel.text= topic.name;

    if ((indexPath.row == 5) || (indexPath.row == 9))
    {
      cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:@"lock_icon.png"]];
      [cell.accessoryView setFrame:CGRectMake(0, 0, 24, 24)];
    } else {
      cell.accessoryView = nil; 
    }

    return cell;
}

为了完成,您也可以像这样使用 Eric 的解决方案 - 它可能会更快,因为 imageView 并不是每次都创建。但这只是很小的区别。可能您的滞后有其他原因。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    if(indexPath.row == 5 || indexPath.row == 9) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCellWithImage"];
        cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:@"lock_icon.png"]];;
        [cell.accessoryView setFrame:CGRectMake(0, 0, 24, 24)];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCell"];
    }

    GPBTopic *topic = [self.topics.list objectAtIndex:indexPath.row];
    cell.textLabel.text= topic.name;

    return cell;
}

关于ios - UITableView cell accessoryView 图片问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15349983/

相关文章:

iOS系统组错误信息

ios - iOS TableView渐变效果

iphone - 表格包含这么多Sections,如何单独增加每一行的Label值

iOS:与sql数据库通信

iphone - 从 iPod 导出歌曲时出现错误

iphone - iOS:使用 CLGeocoder 与 ReverseGeocoding。谷歌地理编码器 API

c - Xcode 中的多个文件

iphone - 无法在 didSelectRowAtIndexPath 中隐藏自定义复选标记

ios - iPhone 数据最佳实践 - 缓存与远程

iOS 企业版 : What should I change or keep the same so an updated app installs over the older version?