Change button background color using swift language
128,480
Solution 1
button.backgroundColor = UIColor.blue
Or any other color: red
, green
, yellow
,etc.
Another option is RGBA color:
button.backgroundColor = UIColor(red: 0.4, green: 1.0, blue: 0.2, alpha: 0.5)
Solution 2
Try this, you need to add the 255
like so:
button.backgroundColor = UIColor(red: 102/255, green: 250/255, blue: 51/255, alpha: 0.5)
Solution 3
Update for xcode 8 and swift 3, specify common colors like:
button.backgroundColor = UIColor.blue
the Color()
has been removed.
Solution 4
If you want to set backgroundColor of button programmatically then this code will surly help you
Swift 3 and Swift 4
self.yourButton.backgroundColor = UIColor.red
Swift 2.3 or lower
self.yourButton.backgroundColor = UIColor.redColor()
Using RGB
self.yourButton.backgroundColor = UIColor(red: 102/255, green: 250/255, blue: 51/255, alpha: 0.5)
or you can use float values
button.backgroundColor = UIColor(red: 0.4, green: 1.0, blue: 0.2, alpha: 0.5)
Solution 5
You can set the background color of a button using the getRed function.
Let's assume you have:
- A UIButton called button, and
- You want to change button's background color to some known RBG value
Then, place the following code in the function where you want to change the background color of your UIButton
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
// This will be some red-ish color
let color = UIColor(red: 200.0/255.0, green: 16.0/255.0, blue: 46.0/255.0, alpha: 1.0)
if color.getRed(&r, green: &g, blue: &b, alpha: &a){
button.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: a)
}
Author by
kalim sayyad
Updated on January 22, 2021Comments
-
kalim sayyad over 3 years
I am new to the swift language. Can someone tell me how to change the background color of a button using the swift language?