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.
                        
preferredFocusEnvironmentswill 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
indexPathForPreferredFocusedViewofUICollectionViewDelegateYou can find more information on this other issue with a similar question and a working example as a response: indexPathForPreferredFocusedView is not being Called