简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM