What control events start and end highlight state of UIButton
Asked Answered
P

2

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.

Publicspirited answered 12/1, 2016 at 13:22 Comment(3)
Do you think you will get any callback to even listen to AllEvents when modified highlighted state from code?Wimberly
If I understand your problem right I think you should use UIControlEventTouchUpInside and UIControlEventTouchUpOutside eventKenspeckle
Maybe use a boolean as an on/off toggle to keep track of the state...Bulbiferous
P
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])
Publicspirited answered 16/1, 2016 at 14:37 Comment(2)
You may also want touchDragEnter to trigger pressedElectrograph
You also probably don't need touchUpOutside since it necessarily happens after touchDragExitElectrograph
S
2

gets highlighted state:UIControlEventTouchDown

lose highlighted state:UIControlEventTouchDragOutside

Stannfield answered 12/1, 2016 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.