change the uiview background color with code
80,831
Solution 1
You can set the backgroundColor
property of whatever view it is you have on screen.
In Objective-C:
self.view.backgroundColor = [UIColor redColor];
In Swift:
self.view.backgroundColor = .red
or if it's the main window you're after,
In Objective-C:
self.window.backgroundColor = [UIColor redColor];
In Swift:
self.window.backgroundColor = .red
Solution 2
self.view.backgroundColor = [UIColor redColor];
possible colors are :
blackColor
darkGrayColor
lightGrayColor
whiteColor
grayColor
redColor
greenColor
blueColor
cyanColor
yellowColor
magentaColor
orangeColor
purpleColor
brownColor
clearColor
Solution 3
For Swift 3, you should do:
self.view.backgroundColor = UIColor.white
Unfortunately, the other answers no longer work in Swift 3.
Solution 4
If you want to change the background color of the view with code in Swift, you should do instead:
self.view.backgroundColor = UIColor.redColor();
Solution 5
You can use RGB Color by following code:
UIColor *myColor = [UIColor colorWithRed:(128.0 / 255.0) green:(90.0 / 255.0)
blue:(200.0 / 255.0) alpha: 1];
self.view.backgroundcolor = mycolor;
Related videos on Youtube
Author by
Rafael
Updated on March 27, 2020Comments
-
Rafael about 4 years
I would like to change the background color of my app programmatically, not IB. Is it possible to get both a Swift and Obj-C answer.
-
fujianjin6471 almost 9 yearsself is not necessary unless in a clousre
-
JimHawkins almost 7 yearsWelcome to stack overflow :-) Please look at How to Answer. You should provide some information why your code solves the problem. Code-only answers aren't useful for the community.
-
Cœur about 5 yearsFor reference, the list of color can be currently found at developer.apple.com/documentation/uikit/uicolor/…
-
Colin Stark over 4 yearsDisagree with @JimHawkins - the problem with SO is not imperfect contribs like the above (which nevertheless have some merit), it's dishearteningly critical comments, often of newbies.
-
JimHawkins over 4 years@ColinStark - there is at least one good reason for code-only answers: the users english is too bad, but the code is helpful as it is. But code-only answers should not be a default on SO . See also meta.stackoverflow.com/q/345719/1988304 . I don't see why my comment should be "dishearteningly"
-
Colin Stark over 4 yearsFirst you said "code-only answers aren't useful", then said "the code is helpful as it is... should not be the default". Which is it? As for disheartening: well, if a newbie is trying her/his best, makes a contribution that's non-null, and immediately gets a negative "this isn't useful" aka "worthless", they may be discouraged. This has occasionally been my experience. It's also the reputation that SO has acquired.