选择时按钮颜色更改

时间:2021-02-26 20:22:59

标签: ios swift uibutton

例如,我有两个按钮(按钮 1 和按钮 2)。

  • 按钮 1 已被选中,其背景颜色为红色,文本颜色为白色。
  • 按钮 2 的背景颜色为灰色,文本颜色为红色。

如果我点击按钮 2,那么背景颜色将为红色,文本颜色为白色。

如果我点击按钮 1,它将变成灰色背景色和红色文本色。

如果我点击按钮 1,那么背景颜色将为红色,文本颜色为白色,按钮 2 将变为灰色背景颜色和红色文本颜色。

那么如何以编程方式执行此操作?

@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button1: UIButton!
    @IBAction func btnbutton2(_ sender: Any) {
        if (buttonTest2.isSelected == false){
        button2.backgroundColor = UIColor.gray
            button2.setTitleColor(UIColor.red, for: .normal)}
        if (button2.isSelected == true){
            button2.backgroundColor = UIColor.systemRed
            button2.setTitleColor(UIColor.white, for: .normal)}
    }
    @IBAction func btnbutton1(_ sender: Any) {
        if (button1.isSelected == true){
            button1.backgroundColor = UIColor.systemRed
            button1.setTitleColor(UIColor.white, for: .normal)}
        if (button1.isSelected == false){
        button1.backgroundColor = UIColor.gray
            button1.setTitleColor(UIColor.red, for: .normal)}
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        button1.backgroundColor = UIColor.systemRed
        button1.setTitleColor(UIColor.white, for: .normal)
        button2.backgroundColor = UIColor.gray
        button2.setTitleColor(UIColor.red, for: .normal)}

1 个答案:

答案 0 :(得分:1)

如果为 Selected 状态设置了颜色,则 UIButtonSelected 属性仅影响标题颜色。

您可以为.normal .highlighted.selected 设置标题颜色——背景颜色没有对应的状态。

此外,点击按钮不会改变它的 Selected 状态……你必须自己做。

试试这个:

class SelectButtonViewController: UIViewController {
    
    @IBOutlet var button1: UIButton!
    @IBOutlet var button2: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        button1.isSelected = true

        // start button1 with "selected" state properties
        button1.backgroundColor = UIColor.systemRed
        button1.setTitleColor(UIColor.red, for: .normal)
        button1.setTitleColor(UIColor.lightGray, for: .highlighted)
        button1.setTitleColor(UIColor.white, for: .selected)

        // start button1 with "not selected" state properties
        button2.backgroundColor = UIColor.gray
        button2.setTitleColor(UIColor.red, for: .normal)
        button2.setTitleColor(UIColor.lightGray, for: .highlighted)
        button2.setTitleColor(UIColor.white, for: .selected)

    }
    
    @IBAction func btnbutton1(_ sender: Any) {
        button1.isSelected = true
        button1.backgroundColor = .systemRed
        button2.isSelected = false
        button2.backgroundColor = .gray
    }
    @IBAction func btnbutton2(_ sender: Any) {
        button2.isSelected = true
        button2.backgroundColor = .systemRed
        button1.isSelected = false
        button1.backgroundColor = .gray
    }

}
相关问题