本文介绍了如何将聚焦的 UICollectionViewCell 居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的很简单:每次用户聚焦一个集合视图单元格时,我想让聚焦的单元格水平居中.看来我目前的方法根本行不通.

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.

推荐答案

诀窍是确保您已设置 UICollectionView scrollEnabled = false.

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)
    }
}

这篇关于如何将聚焦的 UICollectionViewCell 居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-28 02:40