Making the first cell of a UICollectionView focused on tvOS
The way "preferred focus" works conceptually is that there's a "chain" of objects starting at your app's window, going down through view controllers and views, until the chain ends at a focusable view. That view at the end is what will get focused when your app launches, or if focus needs to be reset (for example, if the currently-focused view gets removed from the view hierarchy, UIKit will need to choose another view to become focused). The preferredFocusedView
method is how you define the chain.
For example, UIWindow
implements preferredFocusedView
to return the preferred focused view of the rootViewController
. In the abstract, t's doing something like this:
- (UIView *)preferredFocusedView {
return [self.rootViewController preferredFocusedView];
}
UIViewController
implements preferredFocusedView
to return it's view
property. UIView
just returns itself.
However, UICollectionView
implements preferredFocusedView
differently: in the simplest case, it returns the first cell. So that part of what you want is already done for you. If focus isn't moving to the first cell in your collection, then something higher up in the "chain" is the problem.
If your view controller's collection view isn't the view
property of the view controller, then you'll need to guide the focus chain to the collection yourself:
// in your view controller:
- (UIView *)preferredFocusedView {
return myCollectionView;
}
From there, the collection view will guide the chain to the specific cell.