Apneist Apneist - 1 year ago 90
Swift Question

How to rotate an image cumulatively in Swift ? (Xcode 8)

I am trying to make a button in my view that rotates my image of a gimmicky clock by 45 degrees on each tap of the "rotate" button. All tutorials & answers that I researched online only go to the point where you hit the button once, then it resets (in my case, app only does the action once, then does nothing). So I am trying to make it go from 0 to 45 degrees on the 1st tap, 45 to 90 degrees on 2nd tap, and so on, infinitely, ie store the result every time the button is tapped, then continue from there. Any thoughts? Here is my simple code. Any help would be appreciated as am a newbie in coding - many thanks

@IBAction func Rotate(_ sender: AnyObject) {

let rotation: CGFloat = 0.785398

UIView.animate(withDuration: 0.5) {

self.myWatchImage.transform = CGAffineTransform(rotationAngle: rotation)


Answer Source

Apply rotated:by: to the current transform to get the next one:

@IBAction func doRotate(_ sender: UIButton) {
    let rotation = CGFloat.pi / 4.0
    let transform = myWatchImage.transform
    let rotated = transform.rotated(by: rotation)
    UIView.animate(withDuration: 0.5) {
        self.myWatchImage.transform = rotated
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download