AntonSack AntonSack - 4 months ago 16
iOS Question

UIView.animateWithDuration: animation always stops at original position

I added an

ImageView
in the middle of my view (no constraints set).

With this code I want to move this
ImageView
from its original position to a new one.

Unfortunately, it moves from the new to its original position - why?

let opts = UIViewAnimationOptions.CurveEaseInOut
UIView.animateWithDuration(1, delay: 0, options: opts, animations: {
self.ivSun.center.x += 100
}, completion: nil)

Answer

Add this after completion of your animation.

self.ivSun.layer.position = self.ivSun.layer.presentationLayer().position

I have code that implemented in my game.

        CATransaction.begin()
        CATransaction.setCompletionBlock { () -> Void in
                    self.viewBall.layer.position = self.viewBall.layer.presentationLayer().position
            }
        }
        var animation = CABasicAnimation(keyPath: "position")
        animation.duration = ballMoveTime
        animation.fromValue = NSValue(CGPoint: viewBall.layer.presentationLayer().position)
        animation.toValue = NSValue(CGPoint: CGPointMake(self.borderRight, self.borderMiddle))
        animation.removedOnCompletion = false
        animation.fillMode = kCAFillModeForwards
        viewBall.layer.addAnimation(animation, forKey: "transform")
        CATransaction.commit()

Change position value as you need.