UIAnimate only happens once on button

2019-03-06 02:15发布

问题:

I have a button in my app that has a background image. When the button is pressed I want it to rotate 90 degrees. The code below is my IBAction. It works perfectly the first time, but every other time I press the button it doesn't rotate.

@IBAction func addButton(_ sender: UIButton) {
    UIView.animate(withDuration: 0.05, animations: ({
        sender.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2))
    }))
}

回答1:

You always set the transform to 90 degrees. If you want to rotate an additional 90 degrees each time you tap the button you need to update the existing transform.

sender.transform = sender.transform.rotated(by: CGFloat(Double.pi / 2))