Rotate UIButton 360 degrees

后端 未结 8 890
青春惊慌失措
青春惊慌失措 2021-02-07 01:52

I\'ve been trying to run an animation that rotates my UIButton 360 degrees using this code:

UIView.animateWithDuration(3.0, animations: {
  self.vin         


        
8条回答
  •  天涯浪人
    2021-02-07 02:07

    You can use a little extension based on CABasicAnimation (Swift 4.x):

    extension UIButton {
        func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil) {
            let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
            rotateAnimation.fromValue = 0.0
            rotateAnimation.toValue = CGFloat(.pi * 2.0)
            rotateAnimation.duration = duration
    
            if let delegate: AnyObject = completionDelegate {
                rotateAnimation.delegate = delegate as? CAAnimationDelegate
            }
            self.layer.add(rotateAnimation, forKey: nil)
        }
    }
    

    Usage:

    For example we can start to make a simple button:

    let button = UIButton()
    button.frame = CGRect(x: self.view.frame.size.width/2, y: 150, width: 50, height: 50)
    button.backgroundColor = UIColor.red
    button.setTitle("Name your Button ", for: .normal)
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    self.view.addSubview(button)
    

    Then we can build its selector:

    @objc func buttonAction(sender: UIButton!) {
            print("Button tapped")
            sender.rotate360Degrees()
    }
    

提交回复
热议问题