Reputation: 418
My goal is to call doSomething whenever the user presses "up" on their Apple TV remote, only while the topButton is already focused. The goal is that doSomething should NOT get called if bottomButton was focused. However, when user presses up, the focus moves up to topButton before calling pressesBegan. This causes doSomething to get called regardless of which button was focused.
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()
}
}
Note that this workaround doesn't work:
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
guard let previouslyFocusedItem = context.previouslyFocusedItem as? UIButton else { return }
if previouslyFocusedItem == topButton {
self.doSomething()
}
}
Because the focus doesn't update if user presses up while on topButton.
Which leads to more complicated code (would have to add properties and weird-looking if-statements between the two functions that confuse other developers). Is there a more efficient workaround?
Upvotes: 0
Views: 173
Reputation: 418
Was able to solve it using UIFocusGuide instead. Another issue I found with pressesBegan was that it didn't detect if user swipes up. UIFocusGuide handles both cases.
Upvotes: 0