发现的问题:
自定义一个view,重写它的drawRect方法后,就无法修改这个view的背景颜色,不管是在外部访问这个view,还是在初始化方法中设置,一旦设置backgroundColor这个属性,view的背景色就变成黑色,唯一的例外是在初始化方法中,如果设置self.backgroundColor = [UIColor clearColor]; 背景颜色就变成无色了。
代码如下:
初始化方法:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 这里只能设置无色,其他颜色都是黑色
//self.backgroundColor = [UIColor clearColor];
self.backgroundColor = [UIColor blueColor];
}
return self;
}
drawRect:方法:
- (void)drawRect:(CGRect)rect
{
// 这段代码就是画一条线
// 这里设置背景色是没有效果的
self.backgroundColor = [UIColor blueColor];
UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(100, 33)];
[path addLineToPoint:CGPointMake(200, 33)];
path.lineWidth = 5;
[[UIColor redColor] setStroke];
[path stroke];
}
在网上查资料的过程中,我尝试了一些失败的解决方案,如下:
1)只要在初始化方法里设置背景色就行了,实测不行!而且就算这种方法可行也没用,如果想让view在程序运行过程中修改背景色,这种办法是解决不了的;
2)设置view的opaque(是否不透明)为NO,因为UIView的opaque属性默认是YES,设置为NO就是让view变成透明的,然后就可以设置view的背景色了,具体原因比较复杂,这里不多说了,如果想了解的可以去看这篇文章:
UIView的alpha、hidden和opaque属性之间的关系和区别
然而这种方法也无法解决我的问题!具体原因不知道~~
3)初始化方法里设置viwe的opaque(是否不透明)为NO,同时在drawRect:方法里添加这句代码:CGContextClearRect(context, rect);
具体修改如下:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.opaque = NO;
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// Drawing code
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);//添加这句代码
UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(100, 33)];
[path addLineToPoint:CGPointMake(200, 33)];
path.lineWidth = 5;
[[UIColor redColor] setStroke];
[path stroke];
}
实测还是不管用!
最终我找到了解决办法:
现在还没想到直接设置背景色的办法,我的办法是在drawRect:方法里填充背景色
- (void)drawRect:(CGRect)rect
{
// 下面两句代码的作用就是填充背景色
[[UIColor blueColor] setFill];
UIRectFill(rect);
// 也可以用这两句代码
//CGContextSetFillColorWithColor(context, self.backgroundColor.CGColor);
//CGContextFillRect(context, rect);
UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(100, 33)];
[path addLineToPoint:CGPointMake(200, 33)];
path.lineWidth = 5;
[[UIColor redColor] setStroke];
[path stroke];
}
可以重写一下UIView的setBackgroundColor:方法,以便每次修改背景色,就调用drawRect填充下背景色;
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
[super setBackgroundColor:backgroundColor];
[self setNeedsDisplay];
}
不过实测不重写这个方法也是可以的。
一些题外话:
不得不吐槽一下百度,输入关键字搜索到的都是一些不相关的信息,基本都是广告(各个网站的iOS基础教程贴),但是就是没有这个问题的解决办法,我真的很纳闷以前就没人遇到过这个问题吗?用百度的高级搜索到是能搜到stackoverflow上的几个类似问题,但是只搜到三条!(我输入的关键字是:drawrect background color)
最后还是翻墙用Google,第一页就全是stackoverflow上关于这个问题的解答。以后技术问题还是找谷歌吧~~
附上让我解决问题的stackoverflow上的文章,感谢Pete的提问 和 Avt的解答!感谢stackoverflow,一个神奇的网站~~
UIView Background Color Always Black