How to center UICollectionViewCell that was focused?

狂风中的少年 提交于 2019-12-07 05:17:39

问题


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!



来源:https://stackoverflow.com/questions/32991933/how-to-center-uicollectionviewcell-that-was-focused

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!