Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS animating object goes back to original position

I am trying to animate the position of a UIView object with CABasicAnimation on a button Tap. The object animated and moves to the 'to' position, but returns back to the original position after the animation ends. I want to retain the position of the view object even after the animation ends. This the code snippet that performs the animation. viewObject is the object which I'm trying to animate.

let animation = CABasicAnimation(keyPath: "position")
animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.86, 0, 0.07, 1.0)
animation.duration = 0.5
animation.fromValue = NSValue(cgPoint: CGPoint(x: viewObject.center.x, y: viewObject.center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: viewObject.center.x + 64, y: viewObject.center.y))
viewObject.layer.add(animation, forKey: "position")
like image 758
sarawanak Avatar asked Jul 21 '17 11:07

sarawanak


3 Answers

add following lines before adding animation

animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards

Swift

animation.fillMode = .forwards
animation.isRemovedOnCompletion = false
like image 144
Mohammad Sadiq Avatar answered Oct 16 '22 04:10

Mohammad Sadiq


I think you need to give frame again on completion. So, this can be a nice approach

UIView.animate(withDuration: 0.7, delay: 1.0, options: .curveLinear, animations: {

   let animation = CABasicAnimation(keyPath: "position")
    animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.86, 0, 0.07, 1.0)
    animation.duration = 0.5
    animation.fromValue = NSValue(cgPoint: CGPoint(x: self.viewObject.center.x, y: self.viewObject.center.y))
    animation.toValue = NSValue(cgPoint: CGPoint(x: self.viewObject.center.x + 64, y: self.viewObject.center.y))
    self.viewObject.layer.add(animation, forKey: "position")

}, completion: { finished in
    self.viewObject.frame.origin.x = self.viewObject.frame.origin.x + 64

})

Try this. It will work perfectly

like image 27
Arpit Jain Avatar answered Oct 16 '22 04:10

Arpit Jain


Please add the following code:

Objective-C:

animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;

Swift 4:

animation.fillMode = .forwards
animation.isRemovedOnCompletion = false
like image 7
Saurabh Jain Avatar answered Oct 16 '22 05:10

Saurabh Jain