6

I'm new to tvOS. I would like to have a standard button that once is pressed, it moves the focus to another standard button, how can I do this (if it's possible of course)?

Cue
  • 2,952
  • 3
  • 33
  • 54

2 Answers2

12

Start by overriding the preferredFocusedView in your viewController with a custom property:

var myPreferredFocusedView:UIView?
override var preferredFocusedView: UIView? {
    return myPreferredFocusedView:UIView
}

Then, in your button callback, set the myPreferredFocusedView to your next preferred button which should get focus. After that, directly request a focus update:

func buttonCallback(){
    myPreferredFocusedView = button2 // button2 is an example 

    /*
        Trigger the focus system to re-query the view hierarchy for preferred
        focused views.
    */
    setNeedsFocusUpdate()
    updateFocusIfNeeded()
}

This should update the focus system to your other button.

Antoine
  • 23,526
  • 11
  • 88
  • 94
  • Thank you so much Antoine. It works fine, the only problem I get now is that when leaving the view and then come back, the focus is lost and I need to use the arrow keys (or to drag on the remote) to get any button to have focus. I will try to study more about this... – Cue Oct 14 '15 at 15:23
  • You can use the same code. Just make sure you set the `preferredFocusedView` and request a focus update at the viewWillAppear – Antoine Oct 14 '15 at 18:08
  • @Antoine Can you give me idea to move focus tabar to AVPlayerViewController automatic after 10 seconds programmatically in tvOS. – Vipulk617 Feb 04 '16 at 08:52
  • I tried to move focus tabar to AVPlayerViewController to override preferredFocusedView method but can not move programatically. – Vipulk617 Feb 04 '16 at 08:57
  • @Antoine: Can you help on this https://stackoverflow.com/questions/72478251/swiftui-tvos-handle-focus-for-first-button-on-navigating-downwards-direction – Abhishek Thapliyal Jun 02 '22 at 17:47
5

Another option is to do something like the following, when buttonA (for example) has focus:

buttonB.setNeedsFocusUpdate()
viewController.setNeedsFocusUpdate()

This only works if they're on the same level in the view hierarchy, though. If not then you probably need to chain the calls to setNeedsFocusUpdate all the way up the hierarchy or something...

Read more here

CMash
  • 1,987
  • 22
  • 35