在 ScrollView 中实现自动滚动,使用 UIViewPropertyAnimator:尝试手动滚动时出现故障

时间:2021-03-01 23:22:02

标签: ios objective-c swift uiviewanimation uiviewpropertyanimator

我正在使用 UIViewPropertyAnimator 自动开始滚动 scrollView。

我希望动画在用户开始手动拖动滚动视图时停止。用户基本上可以随时收回对滚动的控制。

不幸的是,当用户开始滚动时会出现故障:触摸 scrollView 时,scrollView 滚动到底部。好像快到动画结尾了。

这是创建错误的代码的最简单版本:

class ViewController: UIViewController {
    
    let scrollView = UIScrollView()
    var scrollingAnimator: UIViewPropertyAnimator?
    
    func startAnimatingScrollView() {
        scrollingAnimator = UIViewPropertyAnimator(duration: 10, curve: .linear) { [weak self] in
            self?.scrollView.contentOffset = CGPoint(x: 0, y: 100)
        }
        scrollingAnimator?.isInterruptible = true
        scrollingAnimator?.isUserInteractionEnabled = true
        scrollingAnimator?.startAnimation()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if scrollingAnimator?.isRunning == true {
            scrollingAnimator?.stopAnimation(true)
        }
    }
}

我尝试过的一些事情:

  • 使用自定义 ScrollView 子类在 touchBegan

    时发送事件
  • 改为调用以下代码:

    scrollingAnimator?.stopAnimation(true) scrollingAnimator?.finishAnimation(at: .current) // 这将调用完成块

  • 请注意,如果我从按钮 (scrollingAnimator?.stopAnimation(true)) 运行相同的代码,它可以完美运行:动画在其当前位置停止,然后用户可以根据需要进行滚动。所以它可能与使用 WillBeginDragging

0 个答案:

没有答案
相关问题