How to move focus at button in collectionview cell in tvos application?

2.8k Views Asked by At

I am working on apple TV application. In my app, I have made a screen which has a collection view. In that case, I am able to move focus at collection view cell but not able to move focus to the button which is in collection view cell so can anyone help me to solve this issue ?

please give me an answer if anyone knows this answer.

2

There are 2 best solutions below

1
On BEST ANSWER

I am able to solve this problem by adding below methods in collectionViewCell subclass.

In CollectionViewCell Subclass

override var preferredFocusEnvironments: [UIFocusEnvironment]{
    // Condition
}
override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool {
    // Condition
}
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
    // Condition
}

you can see more at this link: enter link description here.

0
On

I think this page will guide to achieve what you want. https://developer.apple.com/library/content/documentation/General/Conceptual/AppleTV_PG/WorkingwiththeAppleTVRemote.html#//apple_ref/doc/uid/TP40015241-CH5-SW4

It give good explaination of how focus engine will decide which object should get next focus. Below is great explanation step by step at above link.

Here is an example showing how focus might be determined:

  1. The focus engine asks the root window for its preferredFocusedView, which returns its root view controller’s preferredFocusedView object.
  2. The root view controller, a tab view controller, returns its select view controller’s preferredFocusedView object.
  3. The select view controller overrides its preferredFocusedView method to return a specific UIButton instance.
  4. The UIButton instance returns self(the default), and is focusable, so it is chosen by the focus engine as the next focused view.

You have to override the preferredFoucsedView property of your UIView or UIViewController.

override weak var preferredFocusedView: UIView? {
    if someCondition {
        return theViewYouWant
    } else {
        return defaultView
    }
}

Thanks to Slayter's answer