Shane D Shane D - 4 years ago 298
Swift Question

How to perform an action event in tvOS on button focus

I would like to perform certain actions whenever my button is in focus instead of manually tapping it in


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?

Answer Source

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 {
    // 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download