UITableView单元accessoryView图像问题

min*_*omb 11 xcode uitableview ios

我正在尝试使用以下代码在我的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;
}
Run Code Online (Sandbox Code Playgroud)

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

帮忙,谢谢!

cal*_*kus 21

细胞得到重复使用.您需要每次都重置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;
}
Run Code Online (Sandbox Code Playgroud)

只是为了完成,你也可以像这样使用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;
}
Run Code Online (Sandbox Code Playgroud)