如何在Objective_C中为UIView处理backgroundColor? [英] How is backgroundColor handled for UIView in Objective_C?

查看:125
本文介绍了如何在Objective_C中为UIView处理backgroundColor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩 Apple的示例代码,用于自定义UITableViewCells.我遇到了一些奇怪的行为,使我对backgroundColor的工作原理完全感到困惑.

I have been playing with some of Apple's example code for customizing UITableViewCells. I have run into some weird behavior that has left me completely confused about how backgroundColor works.

以下代码是自定义UITableViewCell中的苹果示例自定义UIView的简化版本.初始化函数将背景色设置为紫色,然后drawRect将背景色设置为绿色.我希望永远不会看到紫色,但这就是我所看到的.通过NSLog语句,我知道正在为每个单元格调用init方法,然后是为每个单元格调用drawRect.绿色设置似乎被忽略了.如果我在初始加载后的任何时间调用[self setNeedsDisplay],则背景正确设置为绿色.

The following code is a much reduced version of Apple's example custom UIView within custom UITableViewCell. The init function sets the background color to purple and then the drawRect sets the background color to green. I would expect to never see purple, but that is all I see. Through NSLog statements I know that the init method is being called for each of the cells, followed by drawRect being called for each of the cells. The green setting seems to be ignored. If I call [self setNeedsDisplay] any time after the initial load, the background is correctly set to green.

- (id)initWithFrame:(CGRect)frame {
    counter = 0;
    if ((self = [super initWithFrame:frame])) {
        self.opaque = YES;
        self.backgroundColor = [UIColor purpleColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect { 
    self.backgroundColor = [UIColor greenColor];
}

有人可以向我解释为什么会这样吗?

Can anyone explain to me why this would be happening like this?

推荐答案

您的-drawRect:实现实际上不会进行任何绘制,因此它本身不会更改任何内容.

Your -drawRect: implementation doesn't actually do any drawing, so it's not going to change anything itself.

大概是通过与您的视图关联的图层来完成绘图.在您的环境中,看起来背景色图层正在绘制其-drawRect:方法之前的绘图.重新绘制图层时,您的-drawRect:方法也恰好被调用.因此,更改背景颜色后,直到再次绘制背景层,您才能看到任何更改,您可以说这是因为您的-drawRect:被再次调用而发生的.

Presumably, the drawing is being done by a layer associated with your view. It looks like, in your environment, the background-colored layer is doing its drawing before your -drawRect: method is called. When the layer redraws, your -drawRect: method also happens to be called. So, after you change the background color, you don't see any changes till the background layer draws again, which you can tell happened because your -drawRect: gets called again.

如果您希望立即应用颜色更改,则需要将视图标记为需要显示,以便使用更改后的背景颜色完全重绘.

If you want the color change to apply immediately, you need to mark your view as needing display, so that it will completely redraw with the changed background color.

这篇关于如何在Objective_C中为UIView处理backgroundColor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆