旋转按钮无限:Swift

Chr*_*man 1 xcode swift

我发现这个代码允许你在Swift中按下按钮时旋转/旋转90度.但我想要做的是在按下按钮时无限旋转/旋转按钮,并在再次按下按钮时停止旋转.这是我的代码:

import UIKit

class ViewController: UIViewController {

  @IBOutlet var otherbutton: UIButton!
  override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view, typically from a                      nib.
}

override func didReceiveMemoryWarning() {
  super.didReceiveMemoryWarning()
  // Dispose of any resources that can be recreated.
}

@IBAction func Rotate(sender: AnyObject) {

  UIView.animateWithDuration(1.0,
  animations: ({

    self.otherbutton.transform = CGAffineTransformMakeRotation(90)

  }))
}

}
Run Code Online (Sandbox Code Playgroud)

Leo*_*bus 6

您可以使用CABasicAnimation无限制地为其设置动画,如下所示:

class ViewController: UIViewController {

    @IBOutlet weak var spinButton: UIButton!

    // create a bool var to know if it is rotating or not
    var isRotating = false

    @IBAction func spinAction(sender: AnyObject) {
        // check if it is not rotating
        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
            spinButton.layer.addAnimation(spinAnimation, forKey: "transform.rotation.z")

        } else { 
            // remove the animation
            spinButton.layer.removeAllAnimations()
        }
        // toggle its state
        isRotating = !isRotating
    }

}
Run Code Online (Sandbox Code Playgroud)