用触摸来回移动物体

时间:2016-02-29 00:46:09

标签: ios swift

我需要在用户触摸屏幕上将对象左右移动。我已经通过用户触摸使对象移动但我想要使对象或图像只能向右或向左移动。我应该使用什么代码来执行此操作?这就是我现在所拥有的。

import UIKit

class ViewController: UIViewController {

    @IBOutlet var Person: UIImageView!
    var location = CGPoint (x: 0, y: 0)

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        let touch : UITouch! = touches.first! as UITouch

        location = touch!.locationInView(self.view)

        Person.center = location

    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

        let touch : UITouch! = touches.first! as UITouch

        location = touch!.locationInView(self.view)

        Person.center = location
    }



    override func viewDidLoad() {
        super.viewDidLoad()
    Person.center = CGPointMake(160, 330)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

1 个答案:

答案 0 :(得分:0)

这应该有效。您可以更改y以更改您希望UIImageView始终保持打开的方式,但请确保两者相同!至少,这应该给你一个想法或让你朝着正确的方向。

import UIKit

class ViewController: UIViewController {

    @IBOutlet var Person: UIImageView!

    var location = CGPoint(x: 0, y: 0)

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        let touch : UITouch! = touches.first! as UITouch

        location = touch!.locationInView(self.view)

        let point = location.x

        Person.center = CGPoint(x: point, y: 160) // change 160 to set vertical height you desire

    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

        let touch : UITouch! = touches.first! as UITouch

        location = touch!.locationInView(self.view)

        let point = location.x

        Person.center = CGPoint(x: point, y: 160) // change 160 to set vertical height you desire
    }



    override func viewDidLoad() {
        super.viewDidLoad()

        Person.center = CGPointMake(160, 330)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

我相信有更好的方法,但我仍然是初学者,所以......