我有一个修改过的UIView,用于显示富文本(NSAttributedString)。我正在将UIView添加到我的UITableViewCell并且正在执行drawRect。为了显示文字,我重写了这种方法。
问题是,在#3行中,它会写出我想要的文本,但在它下面,旧文本仍然存在。
所有其他细胞也是如此。
如何清除每个细胞的UIView?
这是我的直截了当
- (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 :(得分: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]
。