当我以编程方式将UIView
添加到View Controller时,我无法将背景色更改为任何其他颜色,但它始终保持黑色。
- (void)drawRect:(CGRect)rect
{
// Drawing code
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];
}
当我注释掉
drawrect:
并将self.backgroundColor = [UIColor blueColor];
添加到初始化程序时,颜色发生变化:- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor blueColor]
}
return self;
}
为什么会这样,我需要更改什么?实际上,我希望背景透明。
最佳答案
如果使用backgroundColor
自己绘制 View ,则 View 的drawRect
将被忽略。将您的代码更改为
- (void)drawRect:(CGRect)rect
{
// Drawing code
[[UIColor blueColor] setFill]; // changes are here
UIRectFill(rect); // and here
UIBezierPath *path = [[UIBezierPath alloc] init];
[path moveToPoint:CGPointMake(100, 33)];
[path addLineToPoint:CGPointMake(200, 33)];
path.lineWidth = 5;
[[UIColor redColor] setStroke];
[path stroke];
}