如何在Swift中移动图像?

时间:2015-08-21 05:38:55

标签: ios xcode swift

每次按下按钮,我希望能够移动一个物体(在我的情况下,一个图像"小狗")向上移动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 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

你可以这样做。

int i;    
int array1[10];
int array2[10000];

for(i=0;i<100;i++)
   array1[i] = i;

for(i=0;i<10000;i++)
   array2[i] = i+1;

for(i=0;i<100;i++)
  {
     printf("%d \n",array1[i]);
  }

答案 2 :(得分:0)

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替换为图像对象

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