26

当 contentOffset 位于 Swift 的两点之间(请参见下图)时,我想以编程方式设置我的滚动视图的 contentOffset。

问题是,我想为移动添加一个平滑过渡,但我没有找到这方面的文档。我试图做一个循环以逐渐减少内容偏移,但结果不是很好。

在这个例子中,如果内容偏移在滚动结束时小于 150 px,它会平滑(动画的持续时间为 1 秒)到偏移等于 100 的点。最多 150 px,它去到 200 像素。

如果您可以向我提供有关操作的说明(文档或快速示例),那就太好了:)谢谢!

在此处输入图像描述

4

4 回答 4

40

您可以使用UIView.animations

  func goToPoint() {
    dispatch_async(dispatch_get_main_queue()) {
      UIView.animateWithDuration(2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
        self.scrollView.contentOffset.x = 200
        }, completion: nil)
    }
  }

斯威夫特版本

DispatchQueue.main.async {
    UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
        self.myScrollView.contentOffset.x = CGFloat(startingPointForView)
    }, completion: nil)
}

斯威夫特 4

DispatchQueue.main.async {
    UIView.animate(withDuration: 1, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: {
            self.scrollView.contentOffset.x = 200
    }, completion: nil)
}
于 2016-01-20T09:45:28.413 回答
10

这是fatihyildizhan 的代码的Swift 3 版本。

DispatchQueue.main.async {
    UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {
        self.myScrollView.contentOffset.x = CGFloat(startingPointForView)
    }, completion: nil)
}
于 2016-10-03T15:55:36.257 回答
9

现在您可以简单地调用该方法setContentOffset(_ contentOffset: CGPoint, animated: Bool),而不是之前调用混乱动画块的变通方法。看:

x = CGFloat(startingPointForView)
myScrollView.setContentOffset(CGPoint(x: x, y: 0), animated: true)

希望能帮助到你。

于 2018-09-11T19:47:00.420 回答
3

斯威夫特 4:

DispatchQueue.main.async {
    UIView.animate(withDuration: 1, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: {
            self.scrollView.contentOffset.x = 200
    }, completion: nil)
}
于 2019-02-18T19:08:58.080 回答