2016-02-29 48 views
0

我需要根據用戶的手指來回移動圖像。我希望能夠觸摸屏幕,然後圖像會移向我的觸摸。圖像只能左右移動,不能上下移動,我還想增加限制,使圖像可以向屏幕的一側移動多遠。如何在iOS中來回移動對象

我知道這聽起來很多,但我嘗試了很多事情,所有這些都導致了問題。第一次,我能夠點擊並拖動很好的圖像,但當我點擊其他地方時,圖像就會出現在那裏,它不會在那裏出現。

我嘗試的第二件事情讓我拖動圖像,但是當我點擊出來的圖像也不會朝手指動彈。在這一點上,我非常沮喪,並希望得到任何幫助。這是我的代碼。

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet var Person: UIImageView! 


    override func viewDidLoad() { 
     super.viewDidLoad() 

    } 


    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     for touch in (touches){ 
      let location = touch.locationInView(self.view) 




      if Person.frame.contains(location){ 
       Person.center = location 
      } 
     } 
    } 


    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     for touch in (touches){ 
      let location = touch.locationInView(self.view) 




      if Person.frame.contains(location){ 
       Person.center = location 
      } 
     } 
    } 


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


} 
+1

你能編輯*你的問題以顯示你的嘗試代碼嗎? – Paulw11

回答

2

我假設你正在使用touchesBegan(_:withEvent:)touchesMoved(_:withEvent:)獲得觸摸事件。這些方法給你一個UITouch,你可以使用locationInView(_:)轉換爲CGPoint

當觸摸開始時(即touchesBegan(_:withEvent:)),您應該將您的自定義視圖動畫到觸摸的CGPoint。例如: -

UIView.animateWithDuration(0.3, animations: { 

    // Only adjust the x, not the y, to restrict movement to along the x-axis. 
    // You could also check the x value of point to see if reached some limit. 
    self.squareView.frame.origin.x = point.x 
}) 

當移動觸摸屏(即touchesMoved(_:withEvent:)),你應該設置自定義視圖的位置到新的觸摸的CGPoint。例如: -

// Only adjust the x, not the y, to restrict movement to along the x-axis. 
// You could also check the x value of point to see if reached some limit. 
squareView.frame.origin.x = point.x 

一些建議

  1. 只使用前UITouch從集觸摸,這樣你就可以擺脫你的for循環的。
  2. if Person.frame.contains(location){是錯誤的,因爲它僅移動Person如果觸摸是Person內的幀,刪除此並設置在框架的與所述UITouch原點的點(或使用上述我的代碼動畫它)。
+0

我已添加我的代碼以使事情更清晰。 – Jaa4226

+0

我應該如何直接將其實施到我的代碼中? – Jaa4226

+0

我在回答中添加了一些建議。 – paulvs