我正在尝试为自定义集合视图实现“remembersLastFocusedIndexPath”。 Apple文档说:
“如果你是UICollectionView的子类,你也可以通过覆盖preferredFocusEnvironments属性来实现相同的行为,该属性由UIFocusEnvironment协议定义并被所有视图采用。”
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但是当我在“didUpdateFocus”中检查“context.nextFocusedItem”时,它是一个不同的单元格,焦点随机跳转。有人知道,哪里可能有问题?我想不明白。
preferredFocusEnvironments
只允许您指示您的collectionView作为一个整体,是首选焦点环境,但您不能使用它来优先选择单个单元格。
为此,您可以实现indexPathForPreferredFocusedView
的方法UICollectionViewDelegate
您可以通过类似问题和工作示例作为响应找到有关此其他问题的更多信息:indexPathForPreferredFocusedView is not being Called
最后,我不得不将restoresFocusAfterTransition = false设置为视图控制器。它以某种方式殴打。