如何在Swift中移动一张图片?

6

我希望能够在每次按下按钮时将一个对象(在我的情况下,是一张图片“puppy”)向上移动1像素。我已经找到了一些旧的Objective-C解决方案以及类似的Swift代码,但都不适用于我的具体问题。我希望知道一个简单的方法来移动我的图片。这是我目前从收集的代码中得到的(我希望它不必要地长,并且可以缩短到一两行):

@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")
}
3个回答

6

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

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


2
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()

将viewBall替换为您的图像对象

如果您不需要完成块,请将其删除。


1
你可以做到这一点。
func clickButton() {
    UIView.animateWithDuration(animationDuration, animations: {
        let buttonFrame = self.button.frame
        buttonFrame.origin.y = buttonFrame.origin.y - 1.0
        self.button.frame = buttonFrame
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接