Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apple TV force focus another view

I'm working on Apple TV project. The project contains tab bar view controller, normally the tab bar will be appeared when swiping up on remote and hidden when swiping down. But now I reverse that behavior and I want to force focus another view when swiping up(normally focus on tab bar). Any way to do that? Thank you.

like image 709
Cong Phu Avatar asked Feb 05 '23 23:02

Cong Phu


2 Answers

In your UIViewController, override shouldUpdateFocusInContext. If you detect an upward navigation into the tab bar, return false to prevent focus from reaching the tab bar. Then use a combination of preferredFocusEnvironments + setNeedsFocusUpdate to redirect focus somewhere else:

override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool {
  if let nextView: UIView = context.nextFocusedView{
    if ( context.focusHeading == .up &&  nextView.isDescendant(of: tabBar) ){
      changeFocusTo(myView)
      return false
    }
  }
}

internal var viewToFocus: UIView?
func changeFocusTo(_ view:UIView? ){
    viewToFocus = view
    setNeedsFocusUpdate()
}

override var preferredFocusEnvironments: [UIFocusEnvironment]{
    return viewToFocus != nil ? [viewToFocus!] : super.preferredFocusEnvironments
}

This is a generally useful technique for customizing focus updates. An alternative technique is to use UIFocusGuide. You could insert a focus guide underneath the tab bar or surround the tab bar with a focus guide to redirect focus. Though focus guides are useful for simple cases, I have generally had better results using the technique I am describing instead.

like image 138
Rolf Hendriks Avatar answered Feb 13 '23 05:02

Rolf Hendriks


I got the same issue with focus of UITabbarController before and I found the solution in Apple Support

Because UIViewController conforms to UIFocusEnvironment, custom view controllers in your app can override UIFocusEnvironment delegate methods to achieve custom focus behaviors. Custom view controllers can:

Override the preferredFocusedView to specify where focus should start by default. Override shouldUpdateFocusInContext: to define where focus is allowed to move. Override didUpdateFocusInContext:withAnimationCoordinator: to respond to focus updates when they occur and update your app’s internal state. Your view controllers can also request that the focus engine reset focus to the current preferredFocusedView by callingsetNeedsFocusUpdate. Note that calling setNeedsFocusUpdate only has an effect if the view controller contains the currently focused view.

For more detail, please check this link https://developer.apple.com/library/content/documentation/General/Conceptual/AppleTV_PG/WorkingwiththeAppleTVRemote.html#//apple_ref/doc/uid/TP40015241-CH5-SW14

like image 30
Zoom Nguyễn Avatar answered Feb 13 '23 05:02

Zoom Nguyễn