swift - tvOS PressesBegan 调用太晚(焦点已经改变后)
问题描述
我的目标是在用户按下 Apple TV 遥控器上的“向上”键时调用 doSomething,仅当 topButton 已经聚焦时。目标是如果 bottomButton 被聚焦,则不应调用 doSomething。但是,当用户按下时,焦点会在调用 pressesBegan 之前向上移动到 topButton。无论哪个按钮被聚焦,这都会导致 doSomething 被调用。
func doSomething() {
// goal is this function should only run when topButton is focused
}
override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
guard presses.first?.type == UIPress.PressType.upArrow else { return }
print(self.topButton.isFocused)
print(self.bottomButton.isFocused)
if self.topButton.isFocused {
doSomething()
}
}
请注意,此解决方法不起作用:
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
guard let previouslyFocusedItem = context.previouslyFocusedItem as? UIButton else { return }
if previouslyFocusedItem == topButton {
self.doSomething()
}
}
因为如果用户在 topButton 上按下时焦点不会更新。
这会导致更复杂的代码(必须在两个函数之间添加属性和看起来很奇怪的 if 语句,这会让其他开发人员感到困惑)。有没有更有效的解决方法?
解决方案
能够使用 UIFocusGuide 来解决它。我发现 pressesBegan 的另一个问题是它没有检测到用户是否向上滑动。UIFocusGuide 处理这两种情况。