如何在 Swift 中检测 Apple TV 上的按钮突出显示

How to detect button highlight on Apple TV in Swift

我正在制作一个简单的应用程序,当用户将鼠标悬停在按钮上时,它会向用户显示一些信息。我已经四处寻找答案,但似乎还没有人对此感到疑惑。我知道可以检测到按钮突出显示,因为我在我的 Apple TV 上下载的一些应用程序中看到过它。这基本上是我的目标:

@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?"

 }

我知道仅仅创建一个 IBAction func 是行不通的,但我只是用它作为我想做的事情的一个例子。

那么有没有办法检测按钮 highlights/button 悬停以及如何检测?

提前致谢。感谢任何帮助。

通过悬停,我想你的意思是"is the button in focus"。有几种方法可以判断 UI 元素是否处于焦点。

对于 UIViewController,您可以覆盖 didUpdateFocus,它提供有关焦点引擎中发生的事情的上下文。

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")
   }
}

或者在自定义 UIView(即自定义UIButton)中,您可以检查 isFocused 属性.

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