ios - 如何使用 scrollViewWillEndDragging :withVelocity:targetContentOffset to ensure only stops scrolling at two possible positions?

标签 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 - 例如,我仍然可以滚动并停在中间。我怎样才能做到这一点?

最佳答案

也许在 ScrollView 上添加 View 并添加滑动手势,如下所示:

 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)
    }
}

关于ios - 如何使用 scrollViewWillEndDragging :withVelocity:targetContentOffset to ensure only stops scrolling at two possible positions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54151919/

相关文章:

ios - 如何让 Mac OS X 防火墙永久允许我的 iOS 应用程序?

ios - 在 xcode "\\\\\\\"$(SRCROOT)/myprojectname\\\\\\\"中的库搜索路径中,所有这些反斜杠是什么意思?

ios - 我如何才能在整个类(class)中访问约束,而不仅仅是在我设置约束的地方?

ios - swift :键盘行为。为什么 'touchesBegan'使用scrollView时不最小化键盘?

uitableview - 创建动画,例如 iOS 8 Weather App

ios - 数据库中最后插入的行 id 已成功插入但获取该 id 为 0?

ios - 如何从 RESTful API 获取所有数据?

ios - 更改swift4中while循环的声音文件

ios - swift 包管理器中的 "warning: no targets to build in package"错误

ios - 在可滚动列表中快速添加项目