Search code examples
iosswiftuibuttonuicontrolevents

What control events start and end highlight state of UIButton


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.


Solution

  • 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])