Search code examples
iosswiftanimationcgaffinetransform

CGAffineTransformRotate - jump before animation


I'm trying to create an animation rotate image in the button, but the image is jumping before animation, that is, turns 180 degrees and begins the animation

My code:

@IBAction func switchListButtonClick(sender: UIButton) {
    UIView.animateWithDuration(1) {
        self.switchListButton.imageView?.transform = CGAffineTransformRotate((self.switchListButton.imageView?.transform)!, CGFloat(-M_PI_2))
    }
}

I really can't work out why this is happening?

Help me, please.


Solution

  • This works for me

    self.switchListButton.imageView!.clipsToBounds = false;
    self.switchListButton.imageView!.contentMode = .Center;
    
    UIView.animateWithDuration(1) {
    
        self.switchListButton.imageView?.transform = CGAffineTransformRotate((self.switchListButton.imageView?.transform)!, CGFloat(-M_PI_2))
    }
    

    Though not completely sure, I guess image below could illustrate why the code above work. You can see that when you rotate a UIView, the bounds of the view could change and exceed its parent view (above red line in below image), so if you set clipToBounds to true, the transform could fail.

    enter image description here