I am new to the swift language. Can someone tell me how to change the background color of a button using the swift language?
You can set the background color of a button using the getRed function.
Let's assume you have:
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)
}
/*Swift-5 update*/
let tempBtn: UIButton = UIButton(frame: CGRect(x: 5, y: 20, width: 40, height: 40))
tempBtn.backgroundColor = UIColor.red
After you connect the UIButton that you want to change its background as an OUtlet to your ViewController.swift file you can use the following:
yourUIButton.backgroundColor = UIColor.blue
btnLogin.backgroundColor = UIColor.init(colorLiteralRed: (100/255), green: (150/255), blue: (200/255), alpha: 1)
btnLogin.backgroundColor = UIColor.darkGray
U can also play around the tintcolor and button image to indirectly change the color.