【问题标题】:Is there a way to change the focused index path in a collection view?有没有办法更改集合视图中的焦点索引路径?
【发布时间】:2021-10-22 18:59:32
【问题描述】:

我正在构建一个像照片这样的应用程序,您可以在其中滚动浏览 UICollectionView 中照片的缩略图,您可以点击其中一个以全屏查看该照片,然后滑动以在照片之间移动。我正在努力添加对键盘导航的支持,以便您可以使用箭头键选择照片,点击空格键全屏查看,使用箭头键在全屏照片之间移动,然后点击空格键将其关闭。这在照片应用程序中效果很好,但是在我的应用程序中,当您关闭全屏视图控制器时,基础视图控制器中的焦点不会更新到您刚刚关闭的照片的索引路径 - 它显然只知道索引最后一次聚焦在该视图控制器中的路径,即在按下空格之前聚焦的路径。当全屏视图控制器被解除时,我似乎需要手动将焦点移动到可能不同的索引路径。你是怎么做到的?

为了启用焦点,我在UICollectionViewController 中设置了这些:

collectionView.allowsFocus = true
collectionView.allowsFocusDuringEditing = true
collectionView.remembersLastFocusedIndexPath = true
restoresFocusAfterTransition = true

我尝试了以下方法,但焦点并未移至该单元格,即使我将 remembersLastFocusedIndexPathrestoresFocusAfterTransition 设置为 false

cell.focusGroupPriority = .currentlyFocused
cell.setNeedsFocusUpdate()
cell.updateFocusIfNeeded()
cell.becomeFirstResponder()

【问题讨论】:

    标签: ios uicollectionview focus ios15


    【解决方案1】:

    如果已有焦点索引路径,则可以更改焦点索引路径。

    为此,请实现集合视图委托方法indexPathForPreferredFocusedView(in:) 以返回您想要聚焦的索引路径。当你想改变焦点时,调用collectionView.setNeedsFocusUpdate(),系统将调用该函数,让你有机会指定焦点的索引路径。注意 iOS 现在将要求您的应用程序告诉它最初关注哪个索引路径以及随着焦点状态的变化。您可以返回 nil 让系统决定关注哪个。

    请注意,您不能将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
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-23
      • 1970-01-01
      • 2017-01-22
      • 2012-06-27
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多