改变触摸按钮的颜色......然后再返回

时间:2017-02-09 23:11:42

标签: swift uibutton uicolor

我目前有一个UIButton,在选中时会从红色变为绿色。如何实现反向,以便在再次选择时返回到原始状态?以下是我目前的代码:

 @IBAction func button1press(_ sender: AnyObject) {
    (sender as! UIButton).backgroundColor = UIColor.green
    }

2 个答案:

答案 0 :(得分:1)

点击按钮更新所选状态,即: 这样您就可以知道按钮所处的状态。

如果您想编辑其他属性,例如文本颜色,字体,图像等...您可以使用故事板“状态配置”选项,并为不同的状态(在IB的限制范围内)制作不同的主题

@IBAction func button1press(_ sender: AnyObject) {
    if let button : UIButton = sender as? UIButton
    {
        button.isSelected = !button.isSelected

        if (button.isSelected)
        {
            button.backgroundColor = UIColor.green
        }
        else
        {
            button.backgroundColor = UIColor.red
        }
    }
}

答案 1 :(得分:0)

每次按下时,检查当前背景颜色,并将其更改为另一种颜色。

@IBAction func button1press(_ sender: UIButton) {
    if let button = sender as? UIButton {
        if button.backgroundColor == UIColor.green {
            button.backgroundColor = UIColor.red
        }
        else if button.backgroundColor == UIColor.red {
            button.backgroundColor = UIColor.green
        }
    }
}
相关问题