我目前有一个 UIButton,它在被选中时会从红色变为绿色。我怎样才能实现反向,以便在再次选择时回到原来的状态?以下是我当前的代码:
@IBAction func button1press(_ sender: AnyObject) {
(sender as! UIButton).backgroundColor = UIColor.green
}
最佳答案
点击按钮时更新选中状态,即: 这样您就知道按钮处于哪个状态。
如果您想编辑其他属性,例如文本颜色、字体、图像等...您可以只使用 Storyboard的“状态配置”选项,并为不同的状态制作不同的主题(在 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
}
}
}
关于swift - 改变触摸按钮的颜色......然后再回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42148678/