【问题标题】:Changing the color of the button when touch in Swift在 Swift 中触摸时更改按钮的颜色
【发布时间】:2017-02-27 19:59:26
【问题描述】:

我有一个简单的要求,我想在用户触摸按钮时对 UIButton 产生颜色变化效果,我已经浏览了很多链接,但他们建议的内容,有时在我触摸时起作用,我用力触摸然后它起作用,对于正常的触摸它不起作用。

我已经浏览了这个链接。 How to change the background color of a UIButton while it's highlighted?

【问题讨论】:

  • 那么你现在有什么代码?怎么了?或者出了什么问题,您是否遇到任何错误
  • 你能展示你的功能吗
  • 如果我们看不到您的代码是什么样子,就很难调试。

标签: ios swift uibutton highlight


【解决方案1】:

根据您的描述,这应该很容易。请看下面的代码。

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 40))
button.setTitle("Click me", for: .normal)
button.backgroundColor = UIColor.red
button.tintColor = UIColor.white
button.addTarget(self, action: Selector("handleTap"), for: .touchUpOutside)

view.addSubview(button)

func handleTap(sender: UIButton) {

    if sender.backgroundColor == UIColor.red {
         sender.backgroundColor = UIColor.blue
    } else {
         sender.backgroundColor = UIColor.red
    }
}

上面的代码取决于你如何实现你的 UI 以及代码在哪里。如果您可以提供有关您的实施的更多信息,我可以对其进行更新并使其更具体地针对您的情况。

【讨论】:

  • @Scriptable..当按钮被触摸时,它会保持蓝色,但我希望它在变成蓝色后恢复到最后的红色状态。
  • 我已经更新了答案,每次点击时它都会在红色和蓝色之间变化。如果没有你解释你希望它如何工作,我只能做这么多。如果你愿意,你可以让它每次都选择一种随机颜色。只需要添加逻辑。您知道如何更新 backgroundColor 属性,因此您只需编写应用程序逻辑代码以在正确的时间将其更改为所需的颜色
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
相关资源
最近更新 更多