Change button background color using swift language

前端 未结 11 2193
暗喜
暗喜 2020-12-08 13:09

I am new to the swift language. Can someone tell me how to change the background color of a button using the swift language?

相关标签:
11条回答
  • 2020-12-08 13:44

    You can set the background color of a button using the getRed function.
    Let's assume you have:

    1. A UIButton called button, and
    2. 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)
    }
    
    0 讨论(0)
  • 2020-12-08 13:47
    /*Swift-5 update*/
    
    let tempBtn: UIButton = UIButton(frame: CGRect(x: 5, y: 20, width: 40, height: 40))       
    tempBtn.backgroundColor = UIColor.red
    
    0 讨论(0)
  • 2020-12-08 13:49

    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
    
    0 讨论(0)
  • 2020-12-08 13:49

    Swift 3

    Color With RGB

    btnLogin.backgroundColor = UIColor.init(colorLiteralRed: (100/255), green: (150/255), blue: (200/255), alpha: 1)
    

    Using Native color

    btnLogin.backgroundColor = UIColor.darkGray
    
    0 讨论(0)
  • 2020-12-08 13:50

    U can also play around the tintcolor and button image to indirectly change the color.

    0 讨论(0)
提交回复
热议问题