在Apple TV中重新加载后如何在collectionview中保留先前的选择

问题描述 投票:1回答:1

嗨,在我的Apple TV应用程序中,我有一个左侧collectionview右侧collectionview。就像splitview。每当我将焦点放在左侧数据上时,数据就会在右侧刷新,当我在右侧collection视图中选择任何一个单元时,我都会用新的刷新左侧和右侧collectionview数据(如下一级)。在单击菜单时,我将使用旧数据刷新两个集合视图(如上一级)。我想用红色突出显示左collectionview中的单元格,但我要在前进或后退时重新加载左collectionview,所以总是第一个单元格用红色突出显示。任何人都可以建议如何在左侧收藏夹视图中保持先前的选择,因为我仅对左侧菜单使用一个收藏夹视图,只是重新加载数据。

uitableview uicollectionview focus apple-tv
1个回答
0
投票

在UITableView或UICollectionView中保持焦点的最简单方法是使用UICollectionView.remembersLastFocusedIndexPath = true。如果没有先前关注的项目或重新加载了收集视图数据,这将自动将焦点恢复到集合/表视图中最后关注的项目,并且也将自动关注第一个项目。

如果需要更多控制,则下一个级别是从UIViewController设置UICollectionView.remembersLastFocusedIndexPath = false并使用UICollectionViewDelegate.indexPathForPreferredFocusedView。但是,仅当焦点以编程方式更改为集合视图时才调用此方法(但如果由于电视远程交互而将焦点更改为集合视图,则不会调用此方法)。

现在要确保在使用电视遥控器在左右收藏夹视图之间切换时调用indexPathForPreferredFocusedView,您将需要拦截shouldUpdateFocusInContext,以编程方式覆盖左右收藏夹视图之间的焦点切换:

override func shouldUpdateFocusInContext( ... ) -> Bool {
  if let nextView: UIView = context.nextFocusedView, let previousView: UIView = context.previouslyFocusedView{
    if (nextView.isDescendant(of:leftCollectionView) && previousView.isDescendant(of:rightCollectionView)){
      setFocusTo(leftCollectionView) // will invoke delegate indexPath method
      return false // prevent system default focus change in favor of programmatic change
    }
    else if (nextView.isDescendant(of:rightCollectionView && previousView.isDescendant(of:leftCollectionView){
      setFocusTo(rightCollectionView) // will invoke delegate indexPath method
      return false
    }
  }
  return true
}

internal var focusedView: UIView?
internal func setFocusTo(_ view:UIView){
  focusedView = view
  setNeedsFocusUpdate()
}

override var preferredFocusEnvironments -> [UIFocusEnvironment]{
  return focusedView != nil ? [focusedView!] : super.preferredFocusEnvironments
}

func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? { 
  ...
}

或者,您可以只使用setFocusTo(collectionViewCell),而不是使用setFocusTo(collectionView)+ indexPathForPreferredFocusedView。覆盖indexPathForPreferredFocusedView更为健壮,因为它可以捕获所有焦点因用户交互以外的原因而发生转移的所有情况(例如:由于警报显示和关闭而导致系统焦点更新)

© www.soinside.com 2019 - 2024. All rights reserved.