2016-02-29 74 views
0

我需要通过用户触摸在屏幕上将对象左右移动。我已经让这个对象随着用户的触摸而移动,但是我想这样做只能让对象或图像向右或向左移动。我应该用什么代码来做到这一点?这是我现在所拥有的。通过触摸来回移动对象

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. 
    } 


} 

回答

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. 
    } 


} 

我肯定有更好的方法,但我还是一个初学者所以...