contentoffset UIScrollView 的平滑移动 Swift

Smooth move of the contentoffset UIScrollView Swift

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

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

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

如果您能为我提供操作指南(文档或快速示例),那就太好了:)谢谢!

您可以使用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)
    }
  }

Swift版本

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

Swift 4

DispatchQueue.main.async {
    UIView.animate(withDuration: 1, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: {
            self.scrollView.contentOffset.x = 200
    }, completion: nil)
}

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

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

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

希望对您有所帮助。

Swift 4:

DispatchQueue.main.async {
    UIView.animate(withDuration: 1, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: {
            self.scrollView.contentOffset.x = 200
    }, completion: nil)
}