Search code examples
iosswiftcore-animation

Smooth Animation Troubles


I have a button that I am trying to animate to signify sort of a drop down menu effect. Similar to what is seen here

https://medium.com/@phillfarrugia/building-a-tinder-esque-card-interface-5afa63c6d3db

I have used the CGAffineTransform property and converted the degrees to radians to properly rotated. However, the problem comes when I rotate it back the other way. Instead of going back the direction it came it just does somewhat of a akward flip back into the same position.

Could anyone help me rrecreate this smoother transition that is seen in the link I provided

Here is my current code.

@objc func showCalendarPressed(){
    print("show calendar pressed")
    //will check if there has been any animation work done on the UIVIEW
    if self.showCalendar.transform == .identity {

        UIView.animate(withDuration: 1.5) {
            self.showCalendar.transform = CGAffineTransform(rotationAngle: self.radians(degrees: 180) )

        }

    }else {
        //there is a transform on it and we need to change it back
        UIView.animate(withDuration: 0.5, animations: {
            //will remove the transform and animate it back
            self.showCalendar.transform = .identity
        }) { (true) in

        }
    }
}

Radians Function

func radians(degrees: Double) -> CGFloat{
    return CGFloat(degrees * .pi / 180)
}

Solution

  • You are going exactly 1/2 way around (maybe slightly more depending on your conversion to radians), and when you return to .identity, it keeps going the same direction because that is closer (the direction with least rotation). Try using a slightly smaller angle initially. I found this to work:

    Replace:

    self.radians(degrees: 180)
    

    with:

    self.radians(degrees: 179.999)
    

    By going just slightly less than 1/2 way around (which will be imperceptible), returning to .identity will rotate the direction it came from.