Search code examples
swiftxcodeuibuttontvosapple-tv

How to detect button highlight on Apple TV in Swift


I am making a simple app that will show the user some information when they hover over a button. I have looked all over for an answer for this but it seems that no one has wondered this yet. I know it is possible to detect button highlights because I have seen it in some apps I downloaded on my Apple TV. Here is basically what I'm aiming for:

@IBAction func firstButton(_ sender: Any) {
//This function would be called when the first button is highlighted/hovered over

label.text = "Hi there"

 }

@IBAction func secondButton(_ sender: Any) {
//This function would be called when the second button is highlighted/hovered over

label.text = "How are you?"

 }

I know that just creating an IBAction func won't do the trick, but I am just using this as an example of what I want to do.

So is there a way to detect button highlights/button hovering and how?

Thanks in advance. Any help is appreciated.


Solution

  • By hover, I think you mean "is the button in focus". There are a couple ways to tell if a UI element is in focus.

    For UIViewController you can override didUpdateFocus which provides context about what happening in the focus engine.

    override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
        if context.nextFocusedView == myButton {
             print("My button is about to be focused")
        }
        else {
             print("My button is NOT in focus")
       }
    }
    

    Or in a custom UIView (ie. a customUIButton) you can check the isFocused property.

    override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
        print(isFocused)
    }