在UIScrollView中覆盖drawRect时的黑色背景

xon*_*rlz 19 iphone objective-c ipad ios

所以我试图在我的UIScrolLView中覆盖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);  

    }

}
Run Code Online (Sandbox Code Playgroud)

Pak*_*toV 21

我想你要搜索的是:

myScrollViewInstance.opaque = NO
Run Code Online (Sandbox Code Playgroud)

之后,滚动视图的背景不再是黑色.


Den*_*ton 14

在我的UIScrollView子类中覆盖drawRect时,我遇到了类似的情况.

简单地覆盖:

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
}
Run Code Online (Sandbox Code Playgroud)

导致了黑色背景而不是我想要的清晰背景而没有覆盖.

我发现这是因为在Interface Builder中将View Background设置为Default并且设置它以Clear Color解决我的问题.

我不确定这是否与您的问题有关,但我认为我会分享,以防它可能会有所帮助.


Ada*_*lan 6

这里的答案在AppleDocs中非常清楚地记录了UIView的drawRect:方法.第一句话是:

此方法的默认实现不执行任何操作.

所以,这里打电话给超级的建议不会有所帮助.其余的答案包含在讨论中:

...如果视图的opaque属性设置为YES,则drawRect:方法必须使用不透明内容完全填充指定的矩形.

这意味着如果您不打算拥有透明背景,则需要实际绘制背景.最正确的方法是使用以下drawRect:模板:

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect]; // optional if a direct UIView-subclass, should be called otherwise.

    CGContextRef context = UIGraphicsGetCurrentContext();
    // Fill the background color, if needed
    if (self.opaque) {
        UIGraphicsPushContext(context);
        CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor);
        CGContextFillRect(context, rect);
        UIGraphicsPopContext();
    }

    // Your code here...
}
Run Code Online (Sandbox Code Playgroud)


S.P*_*.P. 4

这应该有帮助

CGContextSetFillColorWithColor(context, colorBack);
CGContextFillRect(context, self.bounds); 
Run Code Online (Sandbox Code Playgroud)

// 相应地选择边界和 colorBack