Custom subclassed collectionview - preferredFocusEnvironments is called, but view is not focused

996 Views Asked by At

I am trying to implement "remembersLastFocusedIndexPath" for the custom collection view. Apple documentation said:

"If you subclass UICollectionView, you can also implement the same behavior by overriding the preferredFocusEnvironments property, which is defined by the UIFocusEnvironment protocol and adopted by all views."

class MyCollectionView: UICollectionView {
  open override var preferredFocusEnvironments: [UIFocusEnvironment] {
    let sortedVisibleIndexPaths = indexPathsForVisibleItems.sorted(by: {$0 < $1})
    if let visibleIndexPath = sortedVisibleIndexPaths[safe: 1] {
        if let cell = cellForItem(at: visibleIndexPath) {
            return [cell]
        }
    }
    return []
  }

  open override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
        super.didUpdateFocus(in: context, with: coordinator)
        LogUtils.logger.error("!")
  }
}

preferredFocusEnvironments is called but when I check "context.nextFocusedItem" in "didUpdateFocus" it is a different cell and focus jump randomly. Does someone know, where can be a problem? I can not figure it out.

2

There are 2 best solutions below

1
On

preferredFocusEnvironments will only allow you to indicate that your collectionView, as a whole, is the preferred focus environment, but you can not use it to prefer individual cells.

To do that you can implement the method indexPathForPreferredFocusedView of UICollectionViewDelegate

You can find more information on this other issue with a similar question and a working example as a response: indexPathForPreferredFocusedView is not being Called

0
On

Finaly I had to set restoresFocusAfterTransition = false to the view controller. It was somehow beating with that.