正确的scrollViewWillEndDragging代码?

时间:2015-08-18 21:24:06

标签: ios xcode swift uiscrollview uicollectionview

如何让UIScrollView停止在视图末尾拖动,并将其捕捉到正确的位置?我尝试使用下面的代码,但是当它正确减速并且卡入视图顶部的完美位置时,它不允许我向下滚动:

 func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

        let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout

        let itemHeightIncludingSpacing = self.view.frame.height + layout.minimumInteritemSpacing

        var offset = targetContentOffset.memory

        let index = (offset.x + scrollView.contentInset.bottom) / itemHeightIncludingSpacing
        let roundedIndex = round(index)

        offset = CGPoint(x: roundedIndex * itemHeightIncludingSpacing - scrollView.contentInset.bottom, y: -scrollView.contentInset.top)
        targetContentOffset.memory = offset
    }

这是滚动视图的顶部:

enter image description here

这里是底部,它不在你应该看到的位置。它应该与底部偏移值齐平,就像顶部:

enter image description here

如何让滚动像顶部一样停止冲洗?

1 个答案:

答案 0 :(得分:0)

您是否对具有该方法的UIScrollView进行了扩展?它不存在,但scrollViewDidEndDragging(scrollView:UIScrollView,willDecelerate减速:Bool)确实存在。如果这是扩展中的自定义方法,请确保在代码中的某处调用它(如我提到的委托方法)。此外,重置参数对scrollView没有任何作用。我建议采用不同的方法。

我不确定你在这里问的是什么。您是否不希望在内容弹回原位之前将内容拉过屏幕边缘? 如果是这样,您就不需要这种方法。只需将self.myScrollView.bounces = false添加到viewDidLoad()

即可

编辑: 好的,试试吧
func collectionView(collectionView:UICollectionView,layout collectionViewLayout:UICollectionViewLayout,insetForSectionAtIndex section:Int) - &gt; UIEdgeInsets {
        返回UIEdgeInsetsMake(0,0,0,0)
    }