我正在构建一个应用程序,我需要为三个按钮创建重力和旋转。我为我的一个按钮写了一个无限旋转功能,但我不知道如何将它与其他两个按钮联系起来。
import UIKit
class ViewController: UIViewController {
var animator: UIDynamicAnimator?
var gravity: UIGravityBehavior?
var isRotating = false
@IBOutlet var Ball1: UIButton!
@IBOutlet var Ball2: UIButton!
@IBOutlet var Ball3: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.animator = UIDynamicAnimator(referenceView: self.view)
if !isRotating {
// create a spin animation
let spinAnimation = CABasicAnimation()
// starts from 0
spinAnimation.fromValue = 0
// goes to 360 ( 2 * π )
spinAnimation.toValue = M_PI*2
// define how long it will take to complete a 360
spinAnimation.duration = 1
// make it spin infinitely
spinAnimation.repeatCount = Float.infinity
// do not remove when completed
spinAnimation.removedOnCompletion = false
// specify the fill mode
spinAnimation.fillMode = kCAFillModeForwards
// and the animation acceleration
spinAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
// add the animation to the button layer
Ball1.layer.addAnimation(spinAnimation, forKey: "transform.rotation.z")
} else {
// remove the animation
Ball1.layer.removeAllAnimations()
}
// toggle its state
isRotating = !isRotating
}
}
答案 0 :(得分:1)
您可以通过这种方式将动画图层添加到UIButtons
。
Ball2.layer.addAnimation(spinAnimation, forKey: "transform.rotation.z")
Ball3.layer.addAnimation(spinAnimation, forKey: "transform.rotation.z")
以这种方式删除它们
Ball2.layer.removeAllAnimations()
Ball3.layer.removeAllAnimations()