Using Focus Guide on tvOS

(Part 7 of 8)

This is the seventh part of our tvOS Bootcamp. Please check out the previous pages to know more about this series.

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.

Focus Guide

To do this, here’s the relevant code we would like to add inside DetailBackdropView.swift

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 wishlistButton.

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:

Apple Developer Documentation

Using the Focus Guide to Improve your tvOS Apps

Focus in tvOS

In our final tutorial, we will learn how to customize our player to support Video ads.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store