swift - 改变触摸按钮的颜色......然后再回来

标签 swift uibutton uicolor

我目前有一个 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/

相关文章:

coding-style - Swift 中的早期回归/黄金路径

ios - 在 Xcode 上创建重复的 outlets/actions

ios - UIImage 与 UIAlertController 中的 UITextField 重叠

ios - 更改 UIBarButtonItem 标题看起来很糟糕

iphone - ios: colorWithPatternImage ,拉伸(stretch)图像全屏

ios - 使用开关更改整个应用程序中文本、单元格和 View Controller 的颜色

iphone - 如何在 swift 3 中为 iPhone 制作一个重复倒数计时器应用程序,即使在后台时也会每 'x' 分钟触发一次通知

ios - UIButton 在 iOS 7 中无法正常工作

iphone - 显示自定义 UIButton 上的灰色叠加层

objective-c - Objective C UIColor 到 NSString