Search code examples
objective-ctvos

How can I force focus to change to a specific view in tvOS?


I am implementing custom code to handle a click on the Menu button on the Siri Remote. How can I force focus to change to my custom menu when pressing the menu button?


Solution

  • Finally figured it out myself. You have to override the preferredFocusedView property of your UIView or UIViewController.

    In Swift it works like this:

    func myClickHandler() {
        someCondition = true
        self.setNeedsFocusUpdate()
        self.updateFocusIfNeeded()
        someCondition = false
    }
    
    override weak var preferredFocusedView: UIView? {
        if someCondition {
            return theViewYouWant
        } else {
            return defaultView
        }
    }
    

    I can't quite remember how to override getters in Objective-C so if someone want to post that I'll edit the answer.