Uiview子类第一次调用setneedsdisplay时显示为黑色矩形,之后就ok了



我有一个自定义UIView子类,它覆盖了drawrect。视图从数据源获取数据,并将其中一些信息传递给它的委托,视图控制器,将其处理成它需要绘制的字符串。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]];
    }
}

请告诉我是否有其他代码可以帮助解决这个问题。

您是否尝试将self.backgroundColor = [UIColor clearColor];移动到init方法?

你应该只需要运行那一行一次,我可以想象在绘制方法的中间调用它可能会导致一个问题(在第二次调用drawRect时,backgroundColor已经被设置为clearColor,所以UIView可以忽略它,使你的问题消失与第二个setNeedsDisplay调用)

相关内容

  • 没有找到相关文章