内容偏移UIScrollView Swift的平滑移动

Jib*_*eee 20 animation uiscrollview contentoffset swift

我想以编程方式设置我的scrollview的contentOffset,当contentOffset在两点之间时(请参见下图)和Swift.

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

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

如果你可以提供我做什么的指示(文档或快速示例)会很棒:)谢谢!

在此输入图像描述

fat*_*han 27

您可以使用 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)
    }
  }
Run Code Online (Sandbox Code Playgroud)

  • @fatihyildizhan所以使用这个代码,工作就像我的魅力,谢谢!我尝试制作相同但不在`dispatch_async(dispatch_get_main_queue())`并且它无法正常工作,因为在动画中contentOffset设置回0.0.你能解释一下为什么我们需要在`dispatch_async(dispatch_get_main_queue())`中使用这个make来正常工作吗? (2认同)

use*_*902 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)
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

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

x = CGFloat(startingPointForView)
myScrollView.setContentOffset(CGPoint(x: x, y: 0), animated: true)
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。