启动/停止图像视图旋转动画

时间:2017-07-25 14:10:07

标签: ios swift animation

我有一个开始/停止按钮和一个我要旋转的图像视图。

当我按下按钮时,我希望开始旋转,当我再次按下按钮时,图像应该停止旋转。我目前正在使用getResponseHeaders()动画,但我还没有找到一种方法来停止观看动画。

我希望图像旋转,但是当动画停止时,图像不应该返回到起始位置,而是继续动画。

UIView

这是我的代码,但它并不像我那样工作。

5 个答案:

答案 0 :(得分:9)

Swift 3.x

开始动画

let rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
    rotationAnimation.toValue = NSNumber(value: .pi * 2.0)
    rotationAnimation.duration = 0.5;
    rotationAnimation.isCumulative = true;
    rotationAnimation.repeatCount = .infinity;
    self.imageWood?.layer.add(rotationAnimation, forKey: "rotationAnimation")

停止动画

self.imageWood?.layer.removeAnimation(forKey: "rotationAnimation")

Swift 2.x

开始动画

let rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
    rotationAnimation.toValue = NSNumber(double: M_PI * 2.0)
    rotationAnimation.duration = 1;
    rotationAnimation.cumulative = true;
    rotationAnimation.repeatCount = .infinity;
    self.imageWood?.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")

停止动画

self.imageWood?.layer.removeAnimation(forKey: "rotationAnimation")

答案 1 :(得分:2)

使用现有代码,您可以通过以下方式实现

    var isTapped = true

@IBAction func startStopButtonTapped(_ sender: Any) {
    ruotate()
    isTapped = !isTapped
}

func ruotate() {
    if isTapped {
        let rotationAnimation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.toValue = NSNumber(value: Double.pi * 2.0)
        rotationAnimation.duration = 1;
        rotationAnimation.isCumulative = true;
        rotationAnimation.repeatCount = HUGE;
        self.imageWood?.layer.add(rotationAnimation, forKey: "rotationAnimation")
    }else{
        self.imageWood?.layer.removeAnimation(forKey: "rotationAnimation")
    }
}

答案 2 :(得分:2)

如果使用UIView动画,操作系统仍会创建一个或多个CAAnimation个对象。因此,要停止UIView动画,您仍然可以使用:

myView.layer.removeAllAnimations()

或者,如果您在图层上使用CAAnimation创建动画:

myLayer.removeAllAnimations()

在任何一种情况下,您都可以捕获动画的当前状态,并在删除动画之前将其设置为最终状态。如果您正在对视图的转换进行动画处理,就像在这个问题中那样,那段代码可能如下所示:

func stopAnimationForView(_ myView: UIView) {

  //Get the current transform from the layer's presentation layer
  //(The presentation layer has the state of the "in flight" animation)
  let transform = myView.layer.presentationLayer.transform

  //Set the layer's transform to the current state of the transform
  //from the "in-flight" animation
  myView.layer.transform = transform

  //Now remove the animation 
  //and the view's layer will keep the current rotation
  myView.layer.removeAllAnimations()
}

如果您要为变换以外的属性设置动画,则需要更改上面的代码。

答案 3 :(得分:1)

您的代码使图像旋转2PI角度,但如果您在旋转未结束时单击按钮,动画将在停止前完成,这就是它到达初始位置的原因。

你应该使用CABasicAnimation来使用你可以在任何时候停止保持最后位置的轮换。

答案 4 :(得分:1)

Apple在iOS 10中添加了一个新类UIViewPropertyAnimatorUIViewPropertyAnimator可让您轻松创建基于UIView的动画,可以暂停,反转和来回擦除。

如果您重构代码以使用A UIViewPropertyAnimator,您应该可以暂停和恢复动画。

我有sample project on Github演示使用UIViewPropertyAnimator。我建议看一下。

相关问题