代码之家  ›  专栏  ›  技术社区  ›  BigBoy1337

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

  •  1
  • BigBoy1337  · 技术社区  · 6 年前

    如果用户向上滚动,我希望我的垂直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)
            }
    }
    

    第一个函数永远不会被调用。当我向上或向下滚动时,会正确调用第二个指针,但设置指针对象。Y值似乎不会改变内容偏移量——例如,我仍然可以在中间滚动和停止。我该怎么做?

    1 回复  |  直到 6 年前
        1
  •  0
  •   tbilopavlovic    6 年前

    可能会在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)
        }
    }