When I add a UIView
to a View Controller programmatically I am not able to change the background color to any other color, it always remains black.
- (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];
}
When I comment drawrect:
out and add self.backgroundColor = [UIColor blueColor];
to the initializer the color changes:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor blueColor]
}
return self;
}
Why is this and what do I need to change? Actually I would like the background to be transparent.
backgroundColor
of your view is ignored if you draw view yourself usingdrawRect
. Change your code toSet the background color in initWithFrame: method and do your custom drawing inside drawRect:. That should be able to solve your problem. The drawRect: is implemented in order to do custom drawing not to set view specific properties.
or
I struggled for many hours . If its a model segue, set over current context as property. !
As you are implementing
drawRect:
this will override any default drawing of theUIView
.You must set the
opaque
property of your custom view toNO
and clear the context before you render the path:https://developer.apple.com/library/ios/documentation/uikit/reference/uiview_class/uiview/uiview.html#//apple_ref/occ/instp/UIView/opaque