tvOS UICollectionView获取当前焦点物品的索引路径
所以这是一个不太清的问题,但我无法弄清楚一个非常简单的方法来检测当前焦点物品的indexPath
。
我环顾四周希望看到一些非常简单的东西,如collectionView.indexPathOfCurrentlyFocusedItem
,但没有发现任何远程关闭。 所以我四处寻找,并试图找到类似的东西UIFocusEnvironment
,UIFocusUpdateContext
试图找到所需的属性,但失败。 所以,我能想出的唯一解决方案就是遍历所有可见单元格,并找到一个将焦点属性设置为true的单元格。tvOS UICollectionView获取当前焦点物品的索引路径
那么有没有更简单更优雅的方式来找到当前重点项目的indexPath
? (除跟踪它通过委托方法并将其保存在视图控制器的属性)
使用didUpdateFocusInContect - UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if collectionView == self.collectionView {
print(context.nextFocusedIndexPath)
}
}
这港岛线返回将被集中在小区的indexPath,你也可以尝试:
context.previouslyFocusedIndexPath
取决于你想要做的事情。
可以使用UIScreen
财产focusedView
作为遵循这样的:
if let focusedCell = UIScreen.main.focusedView as? UICollectionViewCell {
if let indexPath = collectionView.indexPath(for: focusedCell) {
print("IndexPath is \(indexPath)")
}
}
这是最完美的答案!谢啦。 –
下面是我在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
}
像魅力一样工作。 +1 – rottenoats
所以,你的目标是做一些事情的时候你得到并失去了特别是在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 ...
感谢您的答案,我自己想出了这一个。但是这需要我将nextFocusedIndexPath存储在一个属性中,而我希望像'collectionView一样更方便。indexPathOfCurrentlyFocusedItem' – xinatanil
是特定索引路径的可能焦点单元格,即我们提供硬编码索引路径 – morroko