ios - 启动/停止 ImageView 旋转动画

标签 ios swift animation

我有一个开始/停止按钮和一个我想旋转的 ImageView 。

当我按下按钮时,我希望图像开始旋转,而当我再次按下按钮时,图像应该停止旋转。我目前正在使用 UIView 动画,但我还没有找到停止 View 动画的方法。

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

var isTapped = true

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

    func ruotate() {
        if isTapped {
            UIView.animate(withDuration: 5, delay: 0, options: .repeat, animations: { () -> Void in
            self.imageWood.transform =     self.imageWood.transform.rotated(by: CGFloat(M_PI_2))
            }, completion: { finished in
            ruotate()
            })
    }  }

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

最佳答案

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")

关于ios - 启动/停止 ImageView 旋转动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45305812/

相关文章:

ios - 键盘在 ios7 (Xcode 6) 中无法正常工作

ios - 如何将日期/时间字符串转换为不同的日期字符串?

ios - 在相机预览 View 上添加按钮 [BESwiftCamera lib]

ios - Swift iOS CoreData 到闪存驱动器(导出和传输)

jQuery 在另一个动画期间向元素添加动画

ios - 在 SwiftUI 中传递 View 或高阶组件

ios - 如何从 Swift 中的 Today Extension 调用父 iPhone 应用程序中的方法?

swift - 按 Swift 中的值对字典进行排序

python - 实时绘制 Pandas 数据框

jquery - 在 jQuery scrollTop 动画期间打印滚动高度