如何在Swift中移动图像? [英] How can I move an image in Swift?

查看:84
本文介绍了如何在Swift中移动图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次按下按钮,我希望能够将对象(在我的情况下,图像小狗)向上移动1个像素。我偶然发现了旧的Objective-C解决方案以及类似的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")
}


推荐答案

这样你就可以改变 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.

这篇关于如何在Swift中移动图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆