Search code examples
objective-cuitableviewtvos

tvOS - Focus particular item in a Table View


In tvOS development - By the default the focus of the table view is the 1st item. But, how to focus particular item by default in a Table View.

For Example, By default, I want to focus the nth row of the table view.

Thanks for your help in advance.

enter image description here


Solution

  • To control the focus engine in general you have to override the methods provided by UIFocusEnvironment and/or the related UITableViewDelegate and UICollectionViewDelegate methods. This behaves much differently than controlling something like the selected row/item, in that it's a global system and not specific to a particular view.

    In your particular case, it may be sufficient to implement the indexPathForPreferredFocusedViewInTableView(_:) method that is available on UITableViewDelegate (note that there is an equivalent method for UICollectionViewDelegate).

    One problem I ran into while attempting to do something similar was how the default chain of preferred focus views works. Eventually I noticed this part of the documentation for UIFocusEnvironment (which all views and view controllers conform to):

    By default, UIView returns itself and UIViewController returns its root view. Returning self in a focusable view indicates that view should be focused. Returning self in an unfocusable view causes the focus engine to pick a default preferred focused view, by finding the closest focusable subview to the top-leading corner of the screen. Returning nil indicates that there is no preferred focused view.

    In my case this meant that the focus engine was picking a default preferred focus view and the focus related delegate methods for my UICollectionView were not being called as I expected. If you find this is the case you may need to implement preferredFocusedView (defined in the UIFocusEnvironment protocol) on your view controller subclass and return your instance of UITableView so that the delegate methods related to focus get invoked reliably.