adman
adman

Reputation: 408

How can I move an image in Swift?

I would like to be able to move an object (in my case, an image "puppy") up 1 pixel every time a button is pressed. I've stumbled upon old Objective-C solutions as well as Swift code that was similar, but none that fit my specific problem. I would love to know an easy way to move my image. This is my code so far from what I could gather(I'm hoping it's unnecessarily long and can be reduced to a line or two):

@IBAction func tapButton() {
UIView.animateWithDuration(0.75, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
            self.puppy.alpha = 1
            self.puppy.center.y = 0
            }, completion: nil)

        var toPoint: CGPoint = CGPointMake(0.0, 1.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")
}

Upvotes: 6

Views: 13282

Answers (3)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

This way you can change a position of your imageView

@IBAction func tapButton() {
    UIView.animateWithDuration(0.75, delay: 0, options: .CurveLinear, animations: {
        // this will change Y position of your imageView center
        // by 1 every time you press button
        self.puppy.center.y -= 1  
    }, completion: nil)
}

And remove all other code from your button action.

Upvotes: 6

Chetan Prajapati
Chetan Prajapati

Reputation: 2297

CATransaction.begin()
CATransaction.setCompletionBlock { () -> Void in
    self.viewBall.layer.position = self.viewBall.layer.presentationLayer().position
}
var animation = CABasicAnimation(keyPath: "position")
animation.duration = ballMoveTime

var currentPosition : CGPoint = viewBall.layer.presentationLayer().position
animation.fromValue = NSValue(currentPosition)
animation.toValue = NSValue(CGPoint: CGPointMake(currentPosition.x, (currentPosition.y + 1)))
animation.removedOnCompletion = false
animation.fillMode = kCAFillModeForwards
viewBall.layer.addAnimation(animation, forKey: "transform")
CATransaction.commit()

Replace viewBall to your image object

And also remove completion block if you don't want.

Upvotes: 2

Rishi
Rishi

Reputation: 2027

You can do this.

func clickButton() {
    UIView.animateWithDuration(animationDuration, animations: {
        let buttonFrame = self.button.frame
        buttonFrame.origin.y = buttonFrame.origin.y - 1.0
        self.button.frame = buttonFrame
    }
}

Upvotes: 1

Related Questions