Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center UICollectionViewCell that was focused?

Tags:

tvos

apple-tv

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.

like image 505
xinatanil Avatar asked Feb 08 '23 21:02

xinatanil


1 Answers

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)
    }
}
like image 59
Daniel Simons Avatar answered Feb 15 '23 11:02

Daniel Simons