How to execute action event in tvOS on button focus

I would like to perform certain actions whenever my button is in focus, rather than manually clicking on it in tvOS.

I have four UIButtons arranged horizontally, and when the user just focuses on one of the 4 buttons, I will show the UIView with some information.

How to perform an action without clicking a button?

+4
source share
1 answer

You can perform your action when one of the buttons becomes focused.

, , . enum .

enum FocusedButtonTag: Int {
    case First // Substitute with names that correspond to button 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 action
        case FocusedButtonTag.Second.rawValue:
            ... // second button action
        case FocusedButtonTag.Third.rawValue:
            ... // third button action
        case FocusedButtonTag.Fourth.rawValue:
            ... // fourth button action
        default:
            break
    }
}
+3

Source: https://habr.com/ru/post/1621675/


All Articles