2016-02-29 75 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. 
    } 


} 

我肯定有更好的方法,但我還是一個初學者所以...