9

I am creating piano-like view with UIButton as piano keys. What UIControlEvents should I listen for to get callbacks when button gets and loses highlighted state?

I tried to make subclass of UIButton and add property observer for highlighted and it was working fine. However sometimes I need to set highlighted state manually from code and that really messes it up as there is no way to tell whether event was user or app initiated.

Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • Do you think you will get any callback to even listen to `AllEvents` when modified highlighted state from code? – zc246 Jan 12 '16 at 13:25
  • If I understand your problem right I think you should use UIControlEventTouchUpInside and UIControlEventTouchUpOutside event – Martin Makarsky Jan 12 '16 at 13:29
  • Maybe use a `boolean` as an on/off toggle to keep track of the state... – l'L'l Jan 12 '16 at 13:33

2 Answers2

20

To mimic piano key behavior I used the following UIControlEvents:

self.addTarget(self, action: "pressed", forControlEvents: [.touchDown])
self.addTarget(self, action: "released", forControlEvents: [.touchDragExit, .touchUpInside, .touchUpOutside, .touchCancel])
Richard Topchii
  • 7,075
  • 8
  • 48
  • 115
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
2

gets highlighted state:UIControlEventTouchDown

lose highlighted state:UIControlEventTouchDragOutside

jiangjiefs
  • 149
  • 11