gpt4 book ai didi

ios - 手动滚动由 UIViewPropertyAnimator 动画的 UIScrollView

转载 作者:行者123 更新时间:2023-12-04 13:51:45 25 4
gpt4 key购买 nike

我有一个 UIScrollView它通过在 UIViewPropertyAnimator 内设置其内容偏移量来自动滚动.自动滚动按预期工作,但是我也希望能够中断动画以手动滚动。
seems to be one of the selling pointsUIViewPropertyAnimator :

...dynamically modify your animations before they finish


然而,它似乎不能很好地与 ScrollView 配合使用(除非我在这里做错了)。
在大多数情况下,它是有效的。当我在动画期间滚动时,它会暂停,然后在减速结束后恢复。然而,当我向底部滚动时,它就像已经在内容的末尾一样(即使它离它很远)。向顶部滚动时这不是问题。
注意到这一点后,我检查了 scrollView.contentOffset 的值。并且似乎卡在最大值+橡皮筋偏移处。我找到了 this question/answer这似乎表明这可能是 UIViewPropertyAnimator 的错误.
我的代码如下:
private var maxYOffset: CGFloat = .zero
private var interruptedFraction: CGFloat = .zero

override func layoutSubviews() {
super.layoutSubviews()

self.maxYOffset = self.scrollView.contentSize.height - self.scrollView.frame.height
}

private func scrollToEnd() {
let maxOffset = CGPoint(x: .zero, y: self.maxYOffset)
let duration = (Double(self.script.wordCount) / Double(self.viewModel.wordsPerMinute)) * 60.0

let animator = UIViewPropertyAnimator(duration: duration, curve: .linear) {
self.scrollView.contentOffset = maxOffset
}
animator.startAnimation()
self.scrollAnimator = animator
}

extension UIAutoScrollView: UIScrollViewDelegate {

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// A user initiated pan gesture will begin scrolling.

if let scrollAnimator = self.scrollAnimator, self.viewModel.isScrolling {
self.interruptedFraction = scrollAnimator.fractionComplete
scrollAnimator.pauseAnimation()
}
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if let scrollAnimator = self.scrollAnimator, self.viewModel.isScrolling {
scrollAnimator.startAnimation()
}
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if let scrollAnimator = self.scrollAnimator, self.viewModel.isScrolling {
scrollAnimator.startAnimation()
}
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
switch scrollView.panGestureRecognizer.state {
case .changed:
// A user initiated pan gesture triggered scrolling.

if let scrollAnimator = self.scrollAnimator {
let fraction = (scrollView.contentOffset.y - self.maxYOffset) / self.maxYOffset
let boundedFraction = min(max(.zero, fraction), 1)

scrollAnimator.fractionComplete = boundedFraction + self.interruptedFraction
}
default:
break
}
}
}
有什么地方明显我出错了吗?或者我可以采用任何解决方法来使 ScrollView 在向下滚动时停止橡皮筋?

最佳答案

您可以添加点击手势识别器并调用此功能,

extension UIScrollView  {
func stopDecelerating() {
let contentOffset = self.contentOffset
self.setContentOffset(contentOffset, animated: false)
}
}

关于ios - 手动滚动由 UIViewPropertyAnimator 动画的 UIScrollView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68658428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com