How to center UICollectionViewCell that was focuse

2019-04-29 12:27发布

问题:

What I want to achieve is very simple: each time user focuses a collection view cell, I want to make the focused cell horizontally centered. It seems like my current approach doesn't work at all.

    func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
        guard collectionView === self.categoryCollectionView else {
            return
        }
        guard let indexPath = context.nextFocusedIndexPath else {
            return
        }

        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: true)
    }

What is odd is that collection view ignores any attempt to scroll anywhere. For testing purposes, I changed index path to the last item's index path in collection view, but it works only when collection view appears for the first time.

回答1:

The trick is to make sure you have set UICollectionView scrollEnabled = false.

override func didUpdateFocusInContext(context: UIFocusUpdateContext, 
  withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    if let focusedView = context.nextFocusedView as? UITableViewCell {
      collectionView.scrollEnabled = false
      let indexPath = collectionView.indexPathForCell(focusedView)!
      collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: true)
    }
}


回答2:

I remember reading somewhere in AirBnB's guide to the Focus Engine that they covered this somewhat. Their code (on GitHub) is for the UIButton class, but hopefully you can draw abstracts for CollectionView from that.

Hope it helps you find the solution!



标签: tvos apple-tv