微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

选择时按钮颜色更改

如何解决选择时按钮颜色更改

例如,我有两个按钮(按钮 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)}

解决方法

如果为 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
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。