【问题标题】:Smooth move of the contentoffset UIScrollView Swiftcontentoffset UIScrollView Swift 的平滑移动
【发布时间】:2015-11-25 14:25:43
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: swift animation uiscrollview contentoffset


    【解决方案1】:

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

    【讨论】:

    • 非常感谢,我用你的代码制作了 Swift 3 版本。编辑 - 我会把它作为答案发布,因为这里的代码很乱。
    • @fatihyildizhan 所以使用了这个代码,就像我的魅力一样,谢谢!我试图做同样的事情,但不是在dispatch_async(dispatch_get_main_queue()) 中,它不能正常工作,因为在动画期间 contentOffset 设置回 0.0。你能解释一下为什么我们需要 dispatch_async(dispatch_get_main_queue()) 中的这个 make 才能正常工作吗?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      希望对你有帮助。

      【讨论】:

        【解决方案4】:

        斯威夫特 4:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-04
          • 1970-01-01
          • 1970-01-01
          • 2014-11-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多