9

所以这是一个很菜的问题,但我只是想不出一种非常简单的方法来检测当前重点项目的indexPath.
我环顾四周,希望能看到一些非常简单的东西,collectionView.indexPathOfCurrentlyFocusedItem但没有找到任何离得很近的东西。所以我四处挖掘并试图找到类似的东西UIFocusEnvironmentUIFocusUpdateContext试图找到所需的属性但失败了。因此,我能想出的唯一解决方案就是遍历所有可见单元格并找到一个具有焦点属性设置为 true 的单元格。

那么有没有更简单优雅的方法来查找当前关注的项目indexPath(除了通过委托方法跟踪它并将其保存在视图控制器的属性中)

4

4 回答 4

20

您可以使用以下UIScreen属性focusedView

if let focusedCell = UIScreen.main.focusedView as? UICollectionViewCell {
    if let indexPath = collectionView.indexPath(for: focusedCell) {
        print("IndexPath is \(indexPath)")
    }
}
于 2015-09-30T11:39:21.933 回答
9

使用didUpdateFocusInContect - UICollectionViewDelegate

func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    if collectionView == self.collectionView {
        print(context.nextFocusedIndexPath)
    }
}

这将返回要聚焦的单元格的 indexPath,您也可以尝试:

context.previouslyFocusedIndexPath

取决于你想要做什么。

于 2015-09-28T07:46:39.167 回答
4

因此,您的目标是在您特别关注 tvOS 下的单元时做一些事情。问题是您正在移动其他 UI 元素,因此上下文可能会有所不同。在这种情况下,您必须只更改您必须关心的那些 UI。

进行实现的正确位置是 func didUpdateFocusInContext(),如下所示:

override func didUpdateFocusInContext(
  context:                              UIFocusUpdateContext,
  withAnimationCoordinator coordinator: UIFocusAnimationCoordinator
) {
  coordinator.addCoordinatedAnimations({
    if let cell = context.previouslyFocusedView as? UICollectionViewCell {
      cell.layer.borderWidth = 2
    }

    if let cell = context.nextFocusedView as? UICollectionViewCell {
      cell.layer.borderWidth = 5
    }
  },
  completion: nil)
}

现在我们使用焦点协调器来应用我们的逻辑:

  • 当先前聚焦的项目是 UICollectionViewCell 时,您必须将焦点释放到下一个项目。您不应该关心下一个项目是什么,因为它可能是集合单元格,也可能不是。为了好玩,在这种情况下,让我们将边框更改为 2。这个值可以默认设置。
  • 当下一个焦点项目是 UICollectionViewCell 时,您必须以类似的方式处理它,否则它将变得一团糟……所以,让我们将边框更改为 5。

如您所见,didUpdateFocusInContext() 为当前视觉上下文中的所有视图提供了一种通用方法。您可以对其他 UI 元素应用相同的方法。

享受 tvOS 的乐趣...

于 2016-06-05T10:06:40.733 回答
2

这就是我如何做到这一点的shouldUpdateFocusInContext

解决方案

override func shouldUpdateFocusInContext(context: UIFocusUpdateContext) -> Bool {

    // The magic is in the next two lines
    let cell: UICollectionViewCell = context.nextFocusedView as! UICollectionViewCell
    let indexPath: NSIndexPath? = self.collectionView.indexPathForCell(cell)

    print(indexPath) 
    // <NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}
    
    return true
}
于 2015-11-09T16:57:24.347 回答