OK, if I have a UIViewController
I can make a view focused on tvOS if I use this `preferredFocusedView but what about making the first cell of a UICollectionView focused? How do I do that?
I have tried to create a UICollectionViewCell
subclass and have the method
- (UIView *)preferredFocusedView {
return ([self ifThisIsTheFirstCell]) ? self : nil;
}
without success.
Is there a way to do that?
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.
I have like an updated answer as (UIView *)preferredFocusedView has become deprecated since TVOS 10 and also actually there is a very easy way to get the first cell and even the last cell focused by default
- (NSArray<id<UIFocusEnvironment>> *)preferredFocusEnvironments
{
return @[myCollectionView.visibleCells.firstObject];
}
Or you can use next code to focus the last Cell
- (NSArray<id<UIFocusEnvironment>> *)preferredFocusEnvironments
{
return @[myCollectionView.visibleCells.lastObject];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With