Reputation: 3637
I have an app where there's an UIImageView
that's being rotated clockwise using UIView.animate
like so:
func startAnimation(targetView: UIView, duration: Double = 6)
{
UIView.animate(withDuration: duration, delay: 0.0, options: .curveLinear, animations: {
targetView.transform = targetView.transform.rotated(by: CGFloat(Double.pi))
})
{ finished in
self.startAnimation(targetView: targetView, duration: duration)
}
}
This function is called in viewDidApear()
only (main reason for that is because I have 2 more UIViewControllers
that the user can go back and forth with.
I also have a stopAnimation()
function that is called in viewWillDisappear()
. Main goal is to stop the animation when the user is being presented with another view controller.
func stopAnimation()
{
self.view.layer.removeAllAnimations()
self.view.layoutIfNeeded()
}
Goal: The animation should be infinite while the user stays on the same view controller, but when they switch to another, the animation should stop and when they go back to that view controller the animation should start again with the same constant velocity.
Problem: For some reason each time you switch between another view controller and the view controller that has that animation, the animation is being sped up. I'm not sure what's causing that.
EDIT: Additional code as requested:
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
startAnimation(targetView: logo)
}
Upvotes: 1
Views: 65
Reputation: 1292
you need to reset the transform every time before you start animating. Otherwise it may well already be half way towards the end of the rotation. Hence taking a shorter time or further away = longer time. Also use .repeat instead of recursion.
func startAnimation(targetView: UIView, duration: Double = 6)
{
targetView.transform = targetView.transform.rotated(by: CGFloat(0.0))
UIView.animate(withDuration: duration, delay: 0.0, options: [.curveLinear, .repeat], animations: {
targetView.transform = targetView.transform.rotated(by: CGFloat(Double.pi))
})
}
Upvotes: 3