如何在Swift中移动图像?

我希望能够每次按下button时将对象(在我的情况下,一个图像“小狗”)移动1像素。 我偶然发现了旧的Objective-C解决scheme以及类似的Swift代码,但没有一个符合我的具体问题。 我很想知道一个简单的方法来移动我的形象。 这是我的代码到目前为止,我可以收集(我希望这是不必要的长,可以减less到一两行):

@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") } 

这样你可以改变你的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) } 

并从您的button操作中删除所有其他代码。

你可以这样做。

 func clickButton() { UIView.animateWithDuration(animationDuration, animations: { let buttonFrame = self.button.frame buttonFrame.origin.y = buttonFrame.origin.y - 1.0 self.button.frame = buttonFrame } } 
 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() 

将viewBallreplace为您的图像对象

如果你不想要,也删除完成块。