2

I want to keep a button in highlighted state image until a second touch to release it to the normal state.

I've try the dispatch_async method, but it simply couldn't be back to normal state after another click.

(I'm coding in Swift so performSelector:WithObject method doesn't work either.)

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Tinyik
  • 457
  • 6
  • 21
  • you can use images to set to UIButton and change them on first click and second click. – Rahul Shirphule Jun 12 '15 at 09:16
  • You cant hold a highlighted state since it automatically gets set/cleared when touch enters/exits during tracking and cleared on up. So you have to use normal and selected state to show your desired image – karthikPrabhu Alagu Jun 12 '15 at 09:39
  • possible duplicate of [How do I toggle hidden of a label while a button is pressed?](http://stackoverflow.com/questions/30743959/how-do-i-toggle-hidden-of-a-label-while-a-button-is-pressed) – nhgrif Jun 12 '15 at 14:52

2 Answers2

7

I will use selected state instead of highlighted. UIButton has already the property so you don't need to create any other property.

button.setImage(image, forState: UIControlState.Normal)
button.setImage(selectedImage, forState: UIControlState.Selected)

button.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside)


func buttonTapped(sender:UIButton)
{
  sender.selected = !sender.selected;
}
agy
  • 2,804
  • 2
  • 15
  • 22
-1

The best solution is extend the UIButton class, add the "highlited" BOOL flag. After each click just update this flag and set different image.