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?
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
}
}