简体   繁体   中英

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.

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 custom UIButton ) you can check the isFocused property.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM