In theory you can easily set the background color via:
self.backgroundColor = [UIColor redColor];
in drawRect, but this does does not have any effect. You can change the view's size, its borders, its subviews, etc., but not background Color. Similar SO queries suggest to add a subView or to change the backgroundColor in the initWithFrame or initWithCoder initialization messages. My question is why does it not work in drawRect when other characteristics can be changed?
Changing the view's layer backgroundColor also does nothing, perhaps for the same reason. What is the relationship between the view's backgroundColor and its layer's backgroundColor, since they are not the same?
Set your background color into your
awakeFromNib
function:Update for swift3 on
drawRect
function :If you set
backgroundColor
when the view is first configured (i.e., before the OS callsdrawRect
), thatbackgroundColor
will be used without any further code on your part. As theUIView
Class Reference says, thebackgroundColor
property is used to "set the view’s color rather than drawing that color yourself."But if you attempt to set it in
drawRect
, the background fill has already been performed, so you won't immediately see the effect of changing the background color (unless you manually perform another fill yourself indrawRect
). ThedrawRect
method should be used for rendering the view, not for configuring it.If the
UIView
sets thebackgroundColor
as the view is being configured (e.g. in whicheverinit
method you avail yourself of), that background color will used, without any need to do anything else indrawRect
.As Rob stated in his answer, the background has already been drawn when the
drawRect
method is called. If you need to change the background color at this point, you will have to draw it yourself:So you still can change the value of the property, but it will not be used until the view is drawn again.