Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you change a UIView background color in drawRect?

Tags:

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?

like image 868
farhadf Avatar asked May 26 '14 15:05

farhadf


People also ask

How do I change the background color in Xcode?

At the top select the attributes inspector. Under the section "View" there should be a spot that says "Background". click that and choose your colour.

How do I change the background color in Viewcontroller?

Find the view or view controller you want to change the background color of. Open it up in the interface builder and open the Attributes Inspector. Find the background color field and set it to the color you want.


1 Answers

If you set backgroundColor when the view is first configured (i.e., before the OS calls drawRect), that backgroundColor will be used without any further code on your part. As the UIView Class Reference says, the backgroundColor 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 in drawRect). The drawRect method should be used for rendering the view, not for configuring it.

If the UIView sets the backgroundColor as the view is being configured (e.g. in whichever init method you avail yourself of), that background color will used, without any need to do anything else in drawRect.

like image 144
Rob Avatar answered Oct 13 '22 00:10

Rob