Search code examples
swift3focusuisplitviewcontrollertvos

Changing the default focus in UISplitViewController


enter image description hereIn an UISplitViewController, by default, the focus is set to be on the TableView. Is there a way for me to override it so that the focus is on the DetailViewController instead?

Can I change the focus to be on the button instead of the TableView cell when starting up the app?


Solution

  • Found the solution:

    override weak var preferredFocusEnvironments: [UIFocusEnvironment] {
        get {
            let controllerToFocus = viewControllers[1] as? ViewController
            return [(controllerToFocus?.view)]
    }
    

    And we need to call setNeedsFocusUpdate() and updateFocusIfNeeded():

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
    
        self.setNeedsFocusUpdate()
        self.updateFocusIfNeeded()
    }