【问题标题】:Why is drawAtPoint Creating Duplicate Images in my tablecell's contentview?为什么 drawAtPoint 在我的表格单元的内容视图中创建重复图像?
【发布时间】:2010-07-22 03:34:26
【问题描述】:

我有一个带有自定义滑块的视图。我们正在使用生成 UITableViewCell 实例的 TableViewController 的子类。在每个 tableViewCell 中,我们将自定义滑块(UI 视图)添加为子视图。在这里,我们有一个用作滑块控制旋钮的视图。它只是带有手势识别器的 UIView 的子类。控制旋钮类的 drawRect 方法采用 UIImage 并执行 drawAtPoint。这很好用!总而言之,我们有:

UITableView -> UITableViewCell -> UITableViewCell.contentView -> SliderView -> SliderKnob -> UIImage

当我们将表格单元格滚动出表格视图时,就会出现问题。旋钮的 UIImage 仍然存在。每次单元格出列时,我们最终都会得到剩余图像的副本。我已经设置了一些 NSLog 语句并确认在每个子视图中都调用了 drawRect。为了刷新单元格的渲染,我需要做些什么吗?我曾尝试在 UITableViewCell 的子视图上使用 setNeedsDisplay,但未能成功防止 UIImage 被复制。

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

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:CellIdentifier] autorelease];
    }

    SliderView *slider = [[[SliderView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 130)] autorelease];

    // Configure the data for the cell.
    NSDictionary *dataItem = [data objectAtIndex:indexPath.row];
    slider.dimensionName = [dataItem objectForKey:@"Name"];
    slider.upperExtreme = [dataItem objectForKey:@"Upper Extreme"];
    slider.lowerExtreme = [dataItem objectForKey:@"Lower Extreme"];
    slider.score = [[dataItem objectForKey:@"Score"] intValue];

    cell.selectionStyle = UITableViewCellEditingStyleNone;
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"track_grainy.png"]];
    [cell.contentView addSubview:slider];

    return cell;
}

【问题讨论】:

  • 有时间可以发一下cellForRowAtIndexPath的方法吗?
  • 当然!我刚刚为你添加了它。

标签: iphone objective-c uiimage drawrect setneedsdisplayinrect


【解决方案1】:

问题在于我们是新手程序员,每次更新单元格时都会分配一个新的 SliderView 实例。这显然是非常糟糕的。我们最终继承了 UITableViewCell 并在它的 init with frame 上实例化了我们的自定义内容视图。通过这样做,我们可以将自定义视图保存在内存中并通过更新单元格来更新它。当单元格从表格视图中释放时,它会被正确释放。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多