xarly
xarly

Reputation: 2144

Custom drawing UIView inside of UITableViewCell

I'm creating a UIView (actually is one of the subviews in the contentView) which draw a stat.

This view is set in each cell of a UITableview.

I configure the cell, in:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellConstant = @"constant";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellConstant forIndexPath:indexPath];

    SCHGraphicView *statView = (SCHGraphicView *)[cell viewWithTag:TAG_STAT_GRAPH];
    [statView setStatValues:[self.listOfListWithValues objectAtIndex:indexPath.row] andBase:10 andColorBar:[UIColor whiteColor]];    

    return cell;
}

This is the drawRect method, which now in test mode I'm drawing just one value.

- (void)drawRect:(CGRect)rect
{
     CGFloat heightCalculate = ([(NSNumber *)[self.statValues objectAtIndex:1]intValue] *self.frame.size.height) / self.base;
    //We create the path
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0,self.frame.size.height - heightCalculate, self.frame.size.width, heightCalculate)];
    path.lineWidth = 0;
    [self.barColor setFill];

    CGContextRef context = UIGraphicsGetCurrentContext();

    //We saved the context
    CGContextSaveGState(context);



    [path fill];
    //Restore the contex
    CGContextRestoreGState(context);
}

Althought I modify the stat values every time in cellForRowAtIndexPath:, these values don't call to [UIView setNeedDisplay] so I don't redraw it each time due to the stat never change in each cell but is different stat if you compare stats between cells.

The problem is when I scroll and I come back to the first cell, this doesn't contains the stat which initially was drawn.

The only way I've achieved that is redraw every time the stat in cellForRowAtIndexPath but I thought a preview was saved in the first time when the view was drawn and this was used to improve the performance and if you call to [UIView setNeedDisplay] the view is redraw again.

Any idea?

Thanks so much

Upvotes: 0

Views: 2368

Answers (1)

Chris Wagner
Chris Wagner

Reputation: 21003

I've experienced strange issues when implementing drawRect: on UITableViewCell and it seems that you should not do it. You should instead create your UIView and add it as a subview of the contentView property. There are many questions/answers on here and across the web about drawRect: and UITableViewCell, most of them suggest that you do not do it.

subclassed UITableViewCell - backgroundView covers up anything I do in drawRect

Upvotes: 1

Related Questions