无法在UITableViewCell的drawRect中绘制

7

我在自定义UITableViewCell的drawRect方法中画图遇到了困难。这是我使用的代码:

- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx  = UIGraphicsGetCurrentContext();
    CGPoint origin    = _faceView.frame.origin;
    CGFloat width     = _faceView.frame.size.width;
    CGFloat height    = _faceView.frame.size.height;
    CGFloat border    = 2.0f;


    CGPoint startPt   = CGPointMake(origin.x + width/2, self.frame.size.height);
    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, startPt.x, startPt.y);

    CGPoint basePt    = CGPointMake(startPt.x, origin.y - height - border);
    CGContextAddLineToPoint(ctx, basePt.x, basePt.y);

    CGRect circleRect = CGRectMake(origin.x - border, origin.y - border, width + 2 * border, height + 2 * border);
    CGContextAddEllipseInRect(ctx, circleRect);

    UIColor *color = [UIColor redColor];
    CGContextSetFillColorWithColor(ctx, color.CGColor);
    CGContextSetStrokeColorWithColor(ctx, color.CGColor);
    CGContextSetLineWidth(ctx, 1.0f);

    CGContextDrawPath(ctx, kCGPathFillStroke);
}

我已经进行了调试,确保所有数字值都是正确的,看起来它们都是正确的。但我真的不知道为什么屏幕上什么也没有显示出来。
就这个问题而言,这是一个在nib中定义的单元格。我使用iOS 7 SDK进行构建。
有什么想法吗?
谢谢。

我同意。除非必要,尽量不要使用drawRect方法,因为它会影响事物运行的性能。 - user2277872
4个回答

15

尝试将背景颜色属性设置为透明色

self.backgroundColor = [UIColor clearColor]

非常感谢您,先生!您帮我省去了很大的麻烦。 - Noob

10

你最好不要在UITableViewCell自己的drawRect方法中这样做。相反,创建一个自定义UIView并将其添加为子视图。

另请参见此答案


3

你需要设置

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
       .....
       [cell setNeedsDisplay];
       return cell;
}

-2
尝试将contentView属性的backgroundColor设置为透明色。
self.contentView = [UIColor clearColor];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接