Search code examples
iosswiftcore-animationcgaffinetransform

iOS Swift: CGAffineTransformMakeRotation resets between roations


I am using a UIRotationGestureRecognizer to rotate a view. When I release the view, then start again, it snaps to the Identity rotation before going back to rotating. I'm trying to figure out how to get it to smoothly continue with the next rotation event. The only question I can find bout this, here, went unanswered years ago.

I can port from Obj-C if anyone is more comfortable responding that way.

I'm sure I am missing something obvious, but you're my only hope, Obi Wan Stackoverflow.

func rotateToRotate(rotationRecognizer: UIRotationGestureRecognizer) {
    let rotation = rotationRecognizer.rotation
    if rotationRecognizer.state == UIGestureRecognizerState.Began {
        self.view.transform = CGAffineTransformMakeRotation(0 + self.lastRotation)
        return
    }

    if rotationRecognizer.state == UIGestureRecognizerState.Ended {
        self.view.transform = CGAffineTransformMakeRotation(rotation)
        self.lastRotation = rotation
        return
    }

    self.view.transform = CGAffineTransformMakeRotation(rotation)
}

Solution

  • Turns out that autocomplete tripped me up here. CGAffineTransformMakeRotation is not the same thing as CGAffineTransformRotate. The former doesn't change the CGAffineTransformIdentity, the latter does.

    Corrected code:

    func rotateToRotate(rotationRecognizer: UIRotationGestureRecognizer) {
        let rotation = rotationRecognizer.rotation
        self.view.transform = CGAffineTransformRotate(self.view.transform, rotation)
        rotationRecognizer.rotation = 0.0
    }