Is there a way to set the UIView background color with Swift?
I know that in Objective-C, you would use self.view.backgroundColor = [UIColor redColor];
, but that does not work the same way in Swift. I have looked around and because Swift is only about a week old, I cannot find an answer.
Does anyone have any suggestions?
The response by @Miknash and @wolfgang gutierrez barrera was helpful to me. Only difference was I had to add
rgbValue:
to the function call.UIColorFromHex(rgbValue: 0xA6D632,alpha: 1 )
like soYou can use the line below which goes into a closure (
viewDidLoad
,didLayOutSubViews
, etc):EDIT Swift 3:
You can use this extension as an alternative if you're dealing with RGB value.
In Swift 3:
Try This, It worked like a charm! for me,
The simplest way to add backgroundColor programmatically by using ColorLiteral.
You need to add the property ColorLiteral, Xcode will prompt you with a whole list of colors in which you can choose any color. The advantage of doing this is we use lesser code, add HEX values or RGB. You will also get the recently used colors from the storyboard.
Follow steps ,
1) Add below line of code in viewDidLoad() ,
and clicked on enter button .
2) Display square box next to =
3) When Clicked on Square Box Xcode will prompt you with a whole list of colors which you can choose any colors also you can set HEX values or RGB
4) You can successfully set the colors .
Hope this will help some one to set backgroundColor in different ways.
I see that this question is solved, but, I want to add some information than can help someone.
if you want use hex to set background color, I found this function and work:
I use this function as follows:
some times you must use
self
:Well that was it, I hope it helps someone .
sorry for my bad english.
this work on iOS 7.1+