1

我有一个覆盖 drawrect 的自定义 UIView 子类。视图从数据源获取数据,并将其中的一些信息传递给它的委托视图控制器,以将其处理成需要绘制的字符串。第一次调用 setneedsdisplay 时,视图显示为黑色矩形,但如果第二次调用它就可以正常工作。所有的帧大小和位置都已正确设置,因此我确信代理和数据源从一开始就已正确设置。这是有问题的drawrect代码:

- (void)drawRect:(CGRect)rect
{

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 2.0);
    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
    CGFloat components[] = {0, 0, 0, 1.0};
    CGColorRef color = CGColorCreate(colorSpace, components);
    ;
    //CGContextStrokeRect(context, CGRectMake(1, 1, self.frame.size.width-1.0, self.frame.size.height-1.0));

    CGContextMoveToPoint(context, 0, [_delegate denominatorPoint:self].y);
        if ([_delegate numeratorBiggerThanDenominator:self]==YES) 
    CGContextAddLineToPoint(context,[[_delegate numeratorString:self]sizeWithFont:[_delegate fontToDrawWith:self]].width , [_delegate denominatorPoint:self].y);
        else
            CGContextAddLineToPoint(context,[[_delegate denominatorString:self]sizeWithFont:[_delegate fontToDrawWith:self]].width , [_delegate denominatorPoint:self].y);
    if ([_delegate hasAFraction:self]==YES) {


    CGContextSetStrokeColorWithColor(context, color);


    CGContextStrokePath(context);

    }

    CGColorSpaceRelease(colorSpace);
    CGColorRelease(color);



    self.backgroundColor=[UIColor clearColor];


    [[_delegate numeratorString:self] drawAtPoint:[_delegate numeratorPoint:self] withFont:[_delegate fontToDrawWith:self]];
    NSLog([_delegate numeratorString:self]);
    if ([_delegate hasAFraction:self]==YES) 
        [[_delegate denominatorString:self] drawAtPoint:[_delegate denominatorPoint:self] withFont:[_delegate fontToDrawWith:self]];
    [[_delegate Variable:self] drawAtPoint:[_delegate variablePoint:self] withFont:[_delegate fontToDrawWith:self]];
    if ([_delegate hasAParenthesTerm:self]==YES) {
        //NSLog(@"parentheses being drawn");
        NSString* openParentheses=@" (";
        [openParentheses drawAtPoint:[_delegate openParenthesesPoint:self] withFont:[_delegate fontToDrawWith:self]];
        NSString* closedParentheses=@")";
        [closedParentheses drawAtPoint:[_delegate closeParenthesesPoint:self] withFont:[_delegate fontToDrawWith:self]];
    }

}

让我知道是否有其他代码可以帮助解决这个问题。

4

1 回答 1

3

您是否尝试self.backgroundColor = [UIColor clearColor];过使用 init 方法?

You should only need to run that line once anyway, and I could imagine that calling it in the middle of the draw method might lead to an issue (and in the second call to drawRect, the backgroundColor would already be set to the clearColor, so UIView could ignore it, making your issue go away with the second setNeedsDisplay call)

于 2013-04-08T00:14:11.293 回答