代码之家  ›  专栏  ›  技术社区  ›  humblePilgrim

表格视图单元格中的图像

  •  0
  • humblePilgrim  · 技术社区  · 15 年前

    我在我的单元格中添加了一个uiImageView作为子视图。然后在其上加上一个标签,使其看起来像一个按钮。但是当表格上下滚动时,图像似乎又被绘制了。这变得非常难看,因为我的图像具有透明效果,一旦输出,它就会丢失。f查看并返回。????

    1 回复  |  直到 15 年前
        1
  •  3
  •   Vladimir    15 年前

    好吧,我想猜一下你的代码是什么样子的:)

    如果图像被绘制多次,这意味着每次表视图查询单元格的数据源时都要添加图像:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView @"SomeID"];
        if (cell == nil) {
            // Create cell
        }
        UIImageView *imView = ... //Create and initialize view
        [cell.contentView addSubview:imView];
        ...
        return cell;
    }
    

    因此,每当您的单元格出现在屏幕上(用户滚动表后),新的图像视图实例就会添加到单元格中。正确的方法是只添加一次图像视图-创建单元时,然后获取并设置现有图像视图:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView @"SomeID"];
        if (cell == nil) {
            // Create cell
            UIImageView *imView = ... //Create and initialize view
            imView.tag = 1000; // or any other int value
            [cell.contentView addSubview:imView];
        }
        UIImageView *iView = (UIImageView *)[cell.contentView viewWithTag:1000];
        iView.image = ...// set required image
        ...
        return cell;
    }
    

    因此,使用这种方法,每次表视图重用单元格时,都会用适合当前行的图像填充现有图像视图。

    我对每个单元格使用了单独的标识符。

    通常这不是一个好主意-在这种情况下,表将无法重用其单元格,您可能会遇到严重的性能问题。

    推荐文章