views:

32

answers:

1

I have a view with a custom slider. We are using a subclass of TableViewController that is generating instances of UITableViewCell. Inside each tableViewCell we add our custom slider (a UI View) as a subview. In here we have a view that serves as the slider's control knob. It is just a subclass of UIView with a gesture recognizer. The drawRect method for the control knob class takes a UIImage and performs drawAtPoint. This works great! To sum up we have:

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

The problem occurs when we scroll a table cell out of the table view. The UIImage for the knob persists. We end up getting a duplicate of the image remaining each time the cell is dequeued. I've setup some NSLog statements and confirmed that drawRect is called in each of the subviews. Is there something I need to do in order to refresh the rendering of the cell? I have tried using setNeedsDisplay on the subviews of the UITableViewCell but have not been successful in preventing the UIImage from being duplicated.

- (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;
}
A: 

The problem was that we were novice programmers and had been allocing a new instance of the SliderView every time a cell was updated. This is obviously very bad. We ended up subclassing UITableViewCell and instantiate our custom content view on it's init with frame. By doing this we could hold the custom view in memory and update it by updating the cell. It then get's properly released when the cells are released from the table view.

Jim Jeffers