我有一个简单的要求,我希望在用户触摸按钮时对UIButton产生变色效果,我已经遍历了许多链接,但是他们的建议是,当我触摸时有时会起作用,我会很努力地触摸它,然后才能正常触摸它没有用。

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

最佳答案

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

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的方式以及代码的位置。如果您可以在自己的实现中提供更多信息,那么我可以对其进行更新,使其更加针对您的情况。

关于ios - 在Swift中触摸时更改按钮的颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40110031/

10-16 23:34