Skip to content

PressButton: a better UIButton for tvOS

Sometimes when developing for tvOS you need to know when a button is pressed and when it is released. Maybe you even need continuous events when the button is being kept pressed.

Unfortunately the only UIControl.event available for UIButton in tvOS is .primaryActionTriggered event, which is triggered one-time-only at the moment the button is pressed, but not while the same button is kept pressed, neither when it is released.

The PressButton class solves this problem. Assign its delegate to your view controller, then implement the protocol PressButtonDelegate to start receiving the events. You can use multiple PressButton in your view controller. Use the sender argument of the delegates to understand which of the button was pressed.

You may have noticed that pressesEnded triggers didCancelPressing(_:) while pressesCancelled triggers didStopPressing(_:).

The behaviour of pressesEnded and pressesCancelled is somehow misleading. At first, I wasn’t understanding why. I was intermittently receiving pressesEnded and pressesCancelled when the button was released. Strange. Then I realized that you receive pressesEnded only if you changed the focus while the button is being pressed. In fact if you don’t change the focus, pressesCancelled is triggered instead. Now, that’s very confusing. This is all to say that you should think about these two events the other way around.

Anyway I just renamed the delegate functions to clarify the correct semantics of the events.

Tags: