2012-11-02 56 views
1

我有一个修改后的UIView,用于显示丰富文本(NSAttributedString)。我将UIView添加到我的UITableViewCell并且正在执行drawRect。为了显示文字,我忽略了这种方法。在UITableViewCell中自定义绘制UIView

问题是,在第3行中,它会写入我想要的文本,但在其下方,旧文本仍然存在。

所有其他单元格也是如此。

如何清除每个单元格的UIView?

这是我的drawRect

- (void)drawRect:(CGRect)rect 
{ 
    [super drawRect:rect]; 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextClearRect(context, self.bounds); 
    CGContextSetTextMatrix(context, CGAffineTransformIdentity); 
    CGContextTranslateCTM(context, 0, self.bounds.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 

    CGMutablePathRef path = CGPathCreateMutable(); //1 
    CGPathAddRect(path, NULL, self.bounds); 

    CTFramesetterRef framesetter = 
    CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self.attString); 

    CTFrameRef frame = 

    CTFramesetterCreateFrame(framesetter, 

         CFRangeMake(0, [self.attString length]), path, NULL); 

    CTFrameDraw(frame, context); //4 
    CFRelease(frame); //5 
    CFRelease(path); 
    CFRelease(framesetter); 

} 

这里是我如何的cellForRowAtIndexPath加入它:

NSAttributedString* attrString = [p attrStringFromMarkup:[NSString stringWithFormat:@"%@%@ %@%@ %@%@", @"<font color=\"black\">", userName, @"<font color=\"gray\">",actionType, @"<font color=\"black\">", object]]; 
CGRect rect = CGRectMake(0, 0, 249, 50); 
CTView *aView = [[CTView alloc]initWithFrame:rect]; 
[aView setBackgroundColor:[UIColor clearColor]]; 
[(CTView*)aView setAttString: attrString]; 
[cell.feedView addSubview:aView]; 
+0

旧文本应该自动清除。 “UIView”或“UITableViewCell”中的drawRect?你能发布这样做的代码吗? –

+0

UIView。我将立即发布我的代码 – Tony

+0

您是否尝试在绘制文本之前绘制大小与单元格大小相同的空矩形?并用它的背景颜色填充它。 – RomanN

回答

2

您应该创建的UITableViewCell后创建CTView只有一次,然后用重用细胞。否则,你会多次添加CTView到同一个单元格。

的代码应该看起来像:

cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[MyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    CGRect rect = CGRectMake(0, 0, 249, 50); 
    CTView *aView = [[CTView alloc]initWithFrame:rect]; 
    [aView setBackgroundColor:[UIColor clearColor]]; 
    [aView setTag:kCTViewTag]; 
    [cell.feedView addSubview:aView]; 
} 

// Configure the cell... 
NSAttributedString* attrString = [p attrStringFromMarkup:[NSString stringWithFormat:@"%@%@ %@%@ %@%@", @"<font color=\"black\">", userName, @"<font color=\"gray\">",actionType, @"<font color=\"black\">", object]]; 

CTView* view = (CTView*)[cell viewWithTag:kCTViewTag]; 
[view setAttString:attrString]; 

setAttString方法应该调用[self setNeedsDisplay]