I have an UIImageView and I would like it so that when I call a function, the image goes from flat(the normal state), to a tilting to the right rotation(say maybe a 20 degree rotation), then back to it's flat(normal) state.
This is what I currently have, but I can't get the desired outcome.
extension UIView {
func rotate(duration: CFTimeInterval = 2) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(20)
rotateAnimation.isRemovedOnCompletion = true
rotateAnimation.duration = duration
rotateAnimation.repeatCount=Float.infinity
self.layer.add(rotateAnimation, forKey: nil)
}
}
UIImageView.rotate()
I tried Creating the above Animation and my tried code Is here
Required Declarations
///View Outlet - Image or UIView
@IBOutlet weak var baseView: UIImageView!
/// Timer - To make Animation in repititive State
var newNAimationTimer : Timer?
/// Plus Degree
let degrees : CGFloat = 20.0
/// Minus Degree
let minusDegree : CGFloat = -20.0
Timer Functions
//MARK: Start Timer
func startTimer()
{
/// Start timer if Timer is Not Initialised Before
if newNAimationTimer == nil {
/// Assign Timer
newNAimationTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(animationVC.animateView), userInfo: nil, repeats: true)
}
}
//MARK: Stop Timer
func stopTimer()
{
///Check Do timer is Initialised
if newNAimationTimer != nil {
/// Yes Stop
newNAimationTimer?.invalidate()
}
}
Timer Handler
/// Animate View With Animations
@objc func animateView()
{
let plusRadian : CGFloat = degrees * CGFloat((Double.pi/180))
let minusRadian : CGFloat = minusDegree * CGFloat((Double.pi/180))
/// First Animation To make View Goes clockwise
UIView.animate(withDuration: 0.5, animations: {
self.baseView.transform = CGAffineTransform(rotationAngle: plusRadian)
}) { (success) in
/// Second Animation to make view go antiClockWise
UIView.animate(withDuration: 0.5, animations: {
self.baseView.transform = CGAffineTransform(rotationAngle: minusRadian)
})
}
}
Button Action
@IBAction func animationButton(_ sender: Any) {
/// Start the Animation
startTimer()
}
ScreenShots
First :
Second:
Running Output