ios – 检测最接近的collectionviewcell到collectionview的中心

前端之家收集整理的这篇文章主要介绍了ios – 检测最接近的collectionviewcell到collectionview的中心前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
怀疑我在下面做了一些根本错误的事情…我有一个水平的集合视图,拖动后我想将最近的单元格捕捉到中心.但我的结果是不可预测的……我在这里做错了什么?
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)
}

猜你在找的iOS相关文章