swiftuibuttontransformuianimation

Immediate UIButton rotation transform, with animated scale


I would like to animate the scale of a UIButton, and animate the scale again when completed, but have it rotate without animation. I've tried to put the rotation transform in an animation call with no duration, but somehow it still makes it part of or replace the scaling animation.

I extended the animation of the scale by a second to demonstrate the result more clearly.

let transforms: CGAffineTransform = .identity

button.transform = transforms

UIView.animate(withDuration: 1.05, delay: 0.0, options: .allowUserInteraction, animations: {
    button.transform = transforms.scaledBy(x: 0.75, y: 0.75)
}, completion: { _ in

        button.transform = CGAffineTransform(rotationAngle: 90 * (.pi/180)) // I want this to happen immediately, without animation

        UIView.animate(withDuration: 1.1, delay: 0.0, options: .allowUserInteraction, animations: {
            button.transform = transforms.scaledBy(x: 1.0, y: 1.0)
        }, completion:nil)

})

Solution

  • You set the rotate transform to happen immediately - and it does! But then you immediately start animating it again, with respect to your transforms variable - reverting its current transform to the one in that variable.

    Instead of using a variable to keep track of the button's transform, just refer to its current transform, like so:

    button.transform = .identity
    UIView.animate(withDuration: 1.05, delay: 0.0, options: .allowUserInteraction, animations: {
        button.transform = button.transform.scaledBy(x: 0.75, y: 0.75)
    }, completion: { _ in
            button.transform = CGAffineTransform(rotationAngle: 90 * (.pi/180)) // I want this to happen immediately, without animation
            UIView.animate(withDuration: 1.1, delay: 0.0, options: .allowUserInteraction, animations: {
                button.transform = button.transform.scaledBy(x: 1.0, y: 1.0)
            }, completion:nil)
    
    })