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];
,
self.view.backgroundColor = UIColor.redColor()
In Swift 3:
self.view.backgroundColor = UIColor.red
You can use this extension as an alternative if you're dealing with RGB value.
extension UIColor {
static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1)
}
}
You can use the line below which goes into a closure (viewDidLoad
, didLayOutSubViews
, etc):
self.view.backgroundColor = .redColor()
EDIT Swift 3:
view.backgroundColor = .red
In Swift 4, just as simple as Swift 3:
self.view.backgroundColor = UIColor.brown
If you want to set your custom RGB color try this:
self.view.backgroundColor = UIColor(red: 20/255.0, green: 106/255.0, blue: 93/255.0, alpha: 1)
Don't forget to keep /255.0 for every color
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 so