我正在构建一个像photos这样的应用程序,你可以在UICollectionView中滚动你的照片的缩略图,你可以点击其中一个来查看全屏照片,然后滑动在照片之间移动。我正在努力增加对键盘导航的支持,这样你就可以使用箭头键来选择一张照片,点击空间来查看全屏照片,使用箭头键在全屏照片之间移动,然后点击空格关闭它。这在Photos应用程序中运行得很好,但在我的应用程序中,当您取消全屏视图控制器时,焦点不会在底层视图控制器中更新到您刚刚删除的照片的索引路径--它显然只知道在视图控制器中最后聚焦的索引路径,即在按下空间之前聚焦的索引路径。似乎我需要手动移动焦点到一个可能不同的索引路径时,全屏视图控制器被取消。你是怎么做到的?
为了启用焦点,我在UICollectionViewController中设置了这些
collectionView.allowsFocus = true
collectionView.allowsFocusDuringEditing = true
collectionView.remembersLastFocusedIndexPath = true
restoresFocusAfterTransition = true我尝试了以下方法,但焦点没有移动到该单元格,即使我将remembersLastFocusedIndexPath和restoresFocusAfterTransition设置为false
cell.focusGroupPriority = .currentlyFocused
cell.setNeedsFocusUpdate()
cell.updateFocusIfNeeded()
cell.becomeFirstResponder()发布于 2021-12-27 03:13:58
如果已经有焦点索引路径,则可以更改聚焦索引路径。
为此,请实现集合视图委托方法indexPathForPreferredFocusedView(in:),以返回希望聚焦的索引路径。当您想要更改焦点时,调用collectionView.setNeedsFocusUpdate(),系统将调用该函数,使您有机会指定要焦点的索引路径。注意,iOS现在将要求您的应用程序告诉它最初要聚焦的索引路径以及焦点状态的变化。您可以返回零,让系统决定重点。
注意,您不能将collectionView.remembersLastFocusedIndexPath设置为true,否则这将无法工作。要获得该功能,您需要使用collectionView(_:didUpdateFocusIn:with:)手动跟踪最后一个聚焦索引路径,并在indexPathForPreferredFocusedView(in:)中返回该路径。
func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? {
return lastFocusedIndexPath
}
func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
lastFocusedIndexPath = context.nextFocusedIndexPath
}
private func moveFocus(to indexPath: IndexPath) {
lastFocusedIndexPath = indexPath
collectionView.setNeedsFocusUpdate()
//collectionView.updateFocusIfNeeded() //can update it now if you need it to
}https://stackoverflow.com/questions/68875444
复制相似问题