如何使用scrollViewWillEndDragging:withVelocity:targetContentOffset来确保仅在两个可能的位置停止滚动?

时间:2019-01-11 18:11:41

标签: ios swift uiscrollview

我希望我的垂直UIScrollView仅在用户向上滚动时在最大内容偏移处停止,或者在用户向下滚动时在最小内容偏移处停止。

我正在使用以下两个功能

func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint,
                         withScrollingVelocity velocity: CGPoint) -> CGPoint {
    return CGPoint(x:0,y:self.scrollView.contentSize.height - self.scrollView.bounds.height)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

        if velocity.y > 0 {
            targetContentOffset.pointee.y = scrollView.contentSize.height - scrollView.bounds.height
        } else { 
            targetContentOffset.pointee.y = CGFloat(0)
        }
}

从不调用第一个函数。当我向上或向下滚动时,第二个被正确调用,但是设置pointee.y值似乎并没有改变contentOffset-例如,我仍然可以滚动并停在中间。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

也许在scrollview上添加视图并添加滑动手势,如下所示:

 var swipeGesture  = UISwipeGestureRecognizer()
    let directions: [UISwipeGestureRecognizer.Direction] = [.up, .down]
    for direction in directions {
        swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(swipeView(_:)))
        view.addGestureRecognizer(swipeGesture)
        swipeGesture.direction = direction
        view.isUserInteractionEnabled = true
        view.isMultipleTouchEnabled = true
    }


    self.view = view
    scrollView.delegate = self


@objc func swipeView(_ sender : UISwipeGestureRecognizer){
    if sender.direction == .up {
        scrollView.setContentOffset(CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.height), animated: true)
    } else if sender.direction == .down {
         scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
    }
}