怀疑我在下面做了一些根本错误的事情…我有一个水平的集合视图,拖动后我想将最近的单元格捕捉到中心.但我的结果是不可预测的……我在这里做错了什么?
func scrollViewDidEndDragging(scrollView: UIScrollView,willDecelerate decelerate: Bool) { // Find collectionview cell nearest to the center of collectionView // Arbitrarily start with the last cell (as a default) var closestCell : UICollectionViewCell = collectionView.visibleCells()[0]; for cell in collectionView!.visibleCells() as [UICollectionViewCell] { let closestCellDelta = abs(closestCell.center.x - collectionView.bounds.size.width/2.0) let cellDelta = abs(cell.center.x - collectionView.bounds.size.width/2.0) if (cellDelta < closestCellDelta){ closestCell = cell } } let indexPath = collectionView.indexPathForCell(closestCell) collectionView.scrollToItemAtIndexPath(indexPath!,atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally,animated: true) }
解决方法
原来我的原始代码丢失了占collecitonview内容偏移.另外,我已将中心移动到scrollViewDidEndDecelerating回调中.我修改了原始代码并将其包含在下面.
func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // Find collectionview cell nearest to the center of collectionView // Arbitrarily start with the last cell (as a default) var closestCell : UICollectionViewCell = collectionView.visibleCells()[0]; for cell in collectionView!.visibleCells() as [UICollectionViewCell] { let closestCellDelta = abs(closestCell.center.x - collectionView.bounds.size.width/2.0 - collectionView.contentOffset.x) let cellDelta = abs(cell.center.x - collectionView.bounds.size.width/2.0 - collectionView.contentOffset.x) if (cellDelta < closestCellDelta){ closestCell = cell } } let indexPath = collectionView.indexPathForCell(closestCell) collectionView.scrollToItemAtIndexPath(indexPath!,animated: true) }