Move and animate UIImageView using swift

Pompey picture Pompey · Jul 17, 2014 · Viewed 15.7k times · Source

I have what should be a fairly simple question here. Basically I'm trying to move an object (a UIImageView) from a point A (where it is set in the storyboard) to a point B which I define programatically.

My first pass through this resulted in this code

        UIView.animateWithDuration(0.75, delay: 0.5, options: UIViewAnimationOptions.CurveLinear, animations: {
            self.signInButton.alpha = 1
            self.signInButton.center.y = 10
        }, completion: nil)

However, what this code does is to basically move the button offcenter and then back to its original location.

I then looked into QuartzCore to help me, but everything is in Objective-C. I have this method:

    func moveImage(view: UIImageView){
        var toPoint: CGPoint = CGPointMake(0.0, -10.0)
        var fromPoint : CGPoint = CGPointZero

        var movement = CABasicAnimation(keyPath: "movement")
        movement.additive = true
        movement.fromValue = fromPoint
        movement.toValue = toPoint
        movement.duration = 0.3

        view.layer.addAnimation(movement, forKey: "move")
    }

However the problem here is that movement.fromValue cannot accept a CGPoint. I know that in objective C there was a function that converted a CGPoint to a NSValue, however this function seems to be deprecated out of Swift and I can't find the other way of doing this.

Therefore my question is either, how do I convert CGPoint to NSValue to make my moveImage() function work, or is there a better way to move an object from point A to point B?

Thanks!

I'm looking at this question Animate UIImage in UIImageView Up & Down (Like it's hovering) Loop

Answer

codester picture codester · Jul 18, 2014

Use NSValue(CGPoint: cgpiont) instead of NSValue.valueWithCGPoint(<#point: CGPoint#>) which is deprecated in swift. NSValue(CGPoint: cgpiont) is constructor given for that which can be used to convert CGPoint to NSValue in swift.Following code will work

func moveImage(view: UIImageView){
    var toPoint: CGPoint = CGPointMake(0.0, -10.0)
    var fromPoint : CGPoint = CGPointZero

    var movement = CABasicAnimation(keyPath: "movement")
    movement.additive = true
    movement.fromValue =  NSValue(CGPoint: fromPoint)
    movement.toValue =  NSValue(CGPoint: toPoint)
    movement.duration = 0.3

    view.layer.addAnimation(movement, forKey: "move")
}