Creating the first tvOS-oriented UICollectionView cell

Well, if I have a UIViewController , I can focus on tvOS if I use this `preferredFocusedView, but how to focus the first cell of the UICollectionView? How to do it?

I tried to subclass UICollectionViewCell and have a method

 - (UIView *)preferredFocusedView { return ([self ifThisIsTheFirstCell]) ? self : nil; } 

without success.

Is there any way to do this?

+5
source share
3 answers

The “preferred focus” principle works conceptually in that there is a “chain” of objects, starting from the window of your application, going down through the view and view controllers until the chain finishes the focused view. This look at the end is what will be focused when your application starts, or if the focus needs to be reset (for example, if the current focus image is removed from the view hierarchy, UIKit will need to select 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 doing something like this:

 - (UIView *)preferredFocusedView { return [self.rootViewController preferredFocusedView]; } 

UIViewController implements preferredFocusedView to return its view property. UIView just returns itself.

However, UICollectionView implements preferredFocusedView in different ways: in the simplest case, it returns the first cell. So part of what you want is already done for you. If the focus does not move to the first cell of your collection, then the problem in the chain is the problem.

If the view of the collection of the view manager is not a view property of the view controller, you need to direct the focus chain to the collection directly:

 // in your view controller: - (UIView *)preferredFocusedView { return myCollectionView; } 

From there, the collection view will direct the chain to a specific cell.

+8
source

You can use this method, Apple documentation

 func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? { return IndexPath(item: self.datasourceArray.count, section: 0) } 

You can return any indexPath that you need.

e.g. IndexPath(item: 0, section: 0)

0
source

You need to add this UICollectionViewDelegate method and any required logic if you don't want to return true in some cases

  func collectionView(collectionView: UICollectionView, shouldUpdateFocusInContext context: UICollectionViewFocusUpdateContext) -> Bool { return true } 
-1
source

Source: https://habr.com/ru/post/1236495/


All Articles