Reputation: 884
I would like to perform certain actions whenever my button is in focus instead of manually tapping it in tvOS
.
I have four UIButtons lined up horizontally and when the user just focuses on one of the 4 buttons, I will be showing an UIView with some information.
How can I perform an action without needing to click the button?
Upvotes: 4
Views: 1273
Reputation: 12582
override func didUpdateFocus(in ctx: UIFocusUpdateContext,
with anco: UIFocusAnimationCoordinator) {
super.didUpdateFocus(in: ctx, with: anco)
if ctx.nextFocusedView == yourButton { .. }
if ctx.nextFocusedView == yourOtherButton { .. }
}
Upvotes: 0
Reputation:
You can perform your action when one of the buttons becomes the focused view.
You could assign a tag to each button, and use the focused button's tag to determine which action to take. For readability, you can define an enum
with values for each tag.
enum FocusedButtonTag: Int {
case First // Substitute with names that correspond to button's title/action
case Second
case Third
case Fourth
}
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator)
guard let button = UIScreen.mainScreen().focusedView as? UIButton else {
return
}
// Update your UIView with the desired information based on the focused button
switch button.tag {
case FocusedButtonTag.First.rawValue:
... // first button's action
case FocusedButtonTag.Second.rawValue:
... // second button's action
case FocusedButtonTag.Third.rawValue:
... // third button's action
case FocusedButtonTag.Fourth.rawValue:
... // fourth button's action
default:
break
}
}
Upvotes: 3