我有一个自定义的UIView子类,它覆盖了drawrect。视图从数据源获取其数据,并将其中的一些信息传递给其委托(视图控制器),以将其处理为需要绘制的字符串。第一次调用setneedsdisplay时,视图显示为黑色矩形,但如果第二次调用它就可以正常工作。所有的帧大小和位置都设置正确,所以我确信委托和数据源从一开始就正确设置。这是令人讨厌的正确代码:
- (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]];
}
}
如果有其他代码可以帮助解决问题,请告诉我。
答案 0 :(得分:3)
您是否尝试将self.backgroundColor = [UIColor clearColor];
移至init方法?
你应该只需要一次运行该行,我可以想象在draw方法中间调用它可能会导致问题(并且在第二次调用drawRect时,backgroundColor已经设置为clearColor,所以UIView可以忽略它,让你的问题随着第二次setNeedsDisplay调用而消失)