0

I have a simple requirement, I want to have color change effect on UIButton when a user touch on button, I have gone through many links but what they suggest, some times work as I touch, I touch hard then it works, for normal touch it does nor work.

I have gone through this link. How to change the background color of a UIButton while it's highlighted?

Community
  • 1
  • 1
Saty
  • 2,563
  • 3
  • 37
  • 88

1 Answers1

0

From what you've described it should be easy. see the code below.

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

The above code depends on how you are implementing your UI and where the code is. if you can prvoide more information on your implementation I can update this and make it more specific to your case.

Scriptable
  • 19,402
  • 5
  • 56
  • 72
  • @Scriptable..this will stay blue when a button is touched but I want it to get back to its last state red after it turns blue. – Saty Oct 19 '16 at 08:08
  • I've updated the answer so that it changes between red and blue everytime you tap. Without you explaining how you want it to work I can only do so much. You could get it to select a random colour everytime if you wanted. just need to add the logic. you know how to update the backgroundColor property so you just need to code your application logic to change it to the required colour at the right time – Scriptable Oct 19 '16 at 08:43