我有一个覆盖 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]];
}
}
让我知道是否有其他代码可以帮助解决这个问题。