2012-11-02 57 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]