4

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.

4

2 回答 2

8

诀窍是确保您已设置 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)
    }
}
于 2015-12-29T05:43:40.697 回答
0

我记得在AirBnB 的 Focus Engine 指南中读到过,他们对此有所了解。他们的代码(在 GitHub 上)用于 UIButton 类,但希望您可以从中为 CollectionView 绘制摘要。

希望它可以帮助您找到解决方案!

于 2015-10-09T14:19:12.550 回答