How to focus a UICollectionViewCell that has been focused?

What I want to achieve is very simple: every time the user focuses the collection view cell, I want to make the focused cell horizontally centered. It seems my current approach does not 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)
    }

It is odd that the collection view ignores any attempt to scroll anywhere. For testing purposes, I changed the index path to the last index path of the element in the collection view, but it only works if the collection view is displayed for the first time.

+4
source share
2 answers

The trick is to make sure you 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)
    }
}
+7

, - AirBnB Focus, . ( GitHub) UIButton, , , CollectionView.

, !

0

Source: https://habr.com/ru/post/1610571/


All Articles