In our Detail screen we saw a peculiar problem.
When we try to scroll up from far right carousel cell, we are not able to focus either Play or Wishlist button. This is a very common issue while developing for tvOS. Specially in screens which do not have too many focusable elements or the focusable elements are simply spread far from each other with no line of sight.
To fix this issue, we need to make use of a technology called UIFocusGuide. As the documentation suggests, UIFocusGuide does not define a new view or participate in the view hierarchy. It rather works like an Auto layout guide.
It primarily defines an invisible focusable region, which can redirect focus to other views in the screen.
In our use-case, we need to define
UIFocusGuide on top of the carousel inside section header in order to redirect focus to Play button when user swipes up from cells that are not directly below the buttons.
To visualize, this is where we would like to add the focus guide.
To do this, here’s the relevant code we would like to add inside
Firstly, we have created a property
focusGuide and inside
setupView() method, we are going to add this guide in this view.
Constraints shown above are basically telling app to create the focus guide at the right of
wishlistButton reaching far right of the superview. We are also aligning it to the bottom of the view and finally setting height same as
Finally, we are setting
focusGuide.preferredFocusEnvironments = [playButton], this tells app to automatically focus the play button whenever this guide comes in focus.
That is all to achieve the desired result. For more complex use-cases, we might need to create multiple focus guides to focus the correct view.
For debugging, we can implement the following method in
DetailViewController and put a breakpoint inside of it:
This method is called whenever there is any update in focus. It can be used to determine the previously focused item, next focused item as well as the direction of focus. Not only that, it is also possible to focus certain view through code in response to a focus.
This is a very critical piece of tvOS. Some good reads/tutorials on focus guide could be found here:
In our final tutorial, we will learn how to customize our player to support Video ads.