Anthony Shahine
Anthony Shahine

Reputation: 2487

ios swift 3 - rotation forwards and backwards

i want to rotate an image in the forward in order to reach 180 degree and then to go back to the first situation (backward with 180 degree)

in fact i see an example on how to rotate an image in one way during one second but i could not understand what should i change in the code to make it rotate in the first 0.5 second - forward and in the next 0.5 second - backward

here is the code :

func addRotation(forLayer layer : CALayer) {
    let rotation : CABasicAnimation = CABasicAnimation(keyPath:"transform.rotation.z")

    rotation.duration = 1.0
    rotation.isRemovedOnCompletion = false
    rotation.repeatCount = HUGE
    rotation.fillMode = kCAFillModeForwards
    rotation.fromValue = NSNumber(value: 0.0)
    rotation.toValue = NSNumber(value: 3.14 * 1.0)
         layer.add(rotation, forKey: "rotate")}

Upvotes: 2

Views: 824

Answers (1)

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

All you need is rotation.autoreverses = true

You can write,

rotation.duration = 5.0
rotation.isRemovedOnCompletion = false
rotation.repeatCount = HUGE
rotation.fromValue = NSNumber(value: 0.0)
rotation.toValue = NSNumber(value: 180 * 0.0174533)
rotation.autoreverses = true
layer.add(rotation, forKey: "rotate")

I have increased animation duration to see it properly you can reduce it to whatever value you want :)

1 Degree = 0.0174533 Radian rotation takes value in radians, hence 180 degree = 180 * 0.0174533

Upvotes: 3

Related Questions