在Swift中触摸时更改按钮的颜色

时间:2016-10-18 13:46:43

标签: ios swift uibutton highlight

我有一个简单的要求,当用户触摸按钮时,我希望在UIButton上有颜色更改效果,我已经通过了许多链接,但是他们建议的是,有时候我触摸工作,我触摸它然后它工作,对于正常触摸,它也不起作用。

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

1 个答案:

答案 0 :(得分:0)

根据您所描述的内容,这应该很容易。请参阅下面的代码。

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的方式以及代码的位置。如果您可以提供有关您的实施的更多信息,我可以更新它并使其更具体针对您的情况。

相关问题