Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I move an image in Swift?

Tags:

xcode

ios

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")
}
like image 959
adman Avatar asked Aug 21 '15 05:08

adman


3 Answers

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.

like image 41
Chetan Prajapati Avatar answered Oct 13 '22 11:10

Chetan Prajapati


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.

like image 114
Dharmesh Kheni Avatar answered Oct 13 '22 12:10

Dharmesh Kheni


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
    }
}
like image 42
Rishi Avatar answered Oct 13 '22 11:10

Rishi