尽管完全是空的drawRect,UIView子类绘制背景: - 为什么?

Pas*_*cal 10 cocoa-touch objective-c uiview iphone-sdk-3.0

所以,我有一个自定义的UIView子类,它可以绘制圆形边.事情完美无缺,但背景总是填满整个边界,尽管首先剪切到路径.边框也绘制在矩形背景上方,尽管我在drawRect中绘制边框:在背景之前.所以我删除了drawRect:的全部内容,现在几乎是空的 - 然而背景被绘制了!

有人对此作出解释吗?我在Interface Builder中设置了backgroundColor.谢谢!

Pas*_*cal 20

对不起这个独白.:)

问题在于UIView的图层显然是绘制了背景,它独立于drawRect:.这就是为什么你不能通过覆盖来摆脱背景drawRect:.

您可以覆盖- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx并使图层绘制您想要的任何内容,或者覆盖- (void) setBackgroundColor:(UIColor *)newColor并不将newColor分配给backgroundColor,而是分配给您自己的ivar,如myBackgroundColor.然后,您可以在drawRect中使用myBackgroundColor ; 按照你喜欢的方式绘制背景.


重写 setBackgroundColor:

定义一个实例变量来保存背景颜色,例如myBackgroundColor.在init方法中,将实际背景颜色设置为clearColor:

- (id) initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super init...])) {
        [super setBackgroundColor:[UIColor clearColor]];
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

覆盖:

- (void) setBackgroundColor:(UIColor *)newColor
{
    if (newColor != myBackgroundColor) {
        [myBackgroundColor release];
        myBackgroundColor = [newColor retain];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在drawRect:方法中使用myBackgroundColor.这样,您可以在代码中使用Interface Builder(或Xcode4)指定的颜色.


Tyl*_*ler 8

这是一个更容易修复:

self.backgroundColor = [UIColor clearColor];
Run Code Online (Sandbox Code Playgroud)


Cra*_*aig 6

我毫不犹豫地建议这个,因为我不想冒犯你,但你有不透明吗?