2017-02-09 40 views
0

我目前有一个UIButton,在选择时从红色变为绿色。我怎样才能实现相反的功能,以便在再次选择时回到原始状态?下面是我当前的代码:改变触摸按钮的颜色...然后再回来

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

与您的问题无关,但如果您将'sender'声明为'UIButton'而不是'AnyObject',则代码将更容易。 – rmaddy

+0

@rmaddy是正确的。如果你这样做,你可以将你的行为绑定到任何UIButton状态 - 包括选定的状态。 – dfd

+0

[如何知道何时按下按钮并取消按钮按下]可能的重复(http://stackoverflow.com/questions/41947279/how-to-know-when-the-button-is-pressed-and-canceled - 按钮按压)。这应该会给你所有你需要的。如果没有,编辑你的问题,我相信我们可以回答。 – dfd

回答

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 
     } 
    } 
} 
+0

非常感谢 - 这很好! –

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 
     } 
    } 
} 
相关问题