所以我尝试在我的UIScrollLView中覆盖drawRect,但是它给我的是黑色背景,而不是我为UIScrollView指定的背景颜色。为什么会这样?如果我删除drawRect代码,那么一切都很好:
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
if (shouldDrawVerticalLineForProfile){
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorRef separatorColor = [UIColor colorWithRed:47.0/255.0 green:47.0/255.0
blue:47.0/255.0 alpha:1.0].CGColor;
// Add at bottom
CGPoint startPoint = CGPointMake(60, 0);
CGPoint endPoint = CGPointMake(60, 10000);
CGContextSaveGState(context);
CGContextSetLineCap(context, kCGLineCapSquare);
CGContextSetStrokeColorWithColor(context, separatorColor);
CGContextSetLineWidth(context, 5.0);
CGContextMoveToPoint(context, startPoint.x + 0.5, startPoint.y + 0.5);
CGContextAddLineToPoint(context, endPoint.x + 0.5, endPoint.y + 0.5);
CGContextStrokePath(context);
CGContextRestoreGState(context);
}
}
6条答案
按热度按时间mftmpeh81#
我猜你要找的是:
之后,滚动视图的背景应该不再是黑色的。
avwztpqn2#
在UIScrollView子类中覆盖drawRect时,我遇到了类似的情况。
简单地重写为:
导致黑色背景,而不是我想要的清晰背景没有覆盖。
我发现这是因为视图背景在Interface Builder中设置为默认,而将其设置为
Clear Color
为我解决了这个问题。我不知道这是否与您的问题有关,但我想我会分享,以防它可能会有所帮助。
4xy9mtcn3#
这里的答案在AppleDocs for UIView的
drawRect:
方法中有非常清楚的记录。此方法的默认实现不执行任何操作。
所以,这里关于调用super的建议不会有什么帮助,答案的其余部分包含在下面的讨论中:
...如果视图的opaque属性设置为YES,则drawRect:方法必须用不透明内容完全填充指定的矩形。
这意味着如果你不想有一个透明的背景,你需要实际绘制背景。最正确的方法是使用下面的
drawRect:
模板:快速更新
由于您负责在自定义视图上添加背景颜色,请确保用颜色填充矩形:
顺便说一句,你也可以在
init
上设置你的自定义视图背景色。这样你就不需要像上面所说的那样用颜色填充矩形了。2skhul334#
这应该会有帮助
//相应地选择边界和颜色返回
jgovgodb5#
请试试这个对我有用
siotufzp6#
唯一有效的方法是在调用
setNeedsDisplay
后显式设置背景。在我的示例中,我使用的是Map上的MKAnnotationView
的子类,而不是UIScrollView
,所以我并不知道这在OP场景中的应用效果如何。在我的示例中,我从setAnnotation
调用setNeedsDisplay
。而且我发现这样做是通过backgroundColor
重置的。在setNeedsDisplay
修复问题后,只需通过backgroundColor
重置即可。FWIW,我也观察到简单地重写
drawRect
以委托给超类会导致这个黑色背景问题。