2015-10-16 97 views
0

我想顯示被觸摸和移動的對象的x corrdinate。swift touchesBegan並將其顯​​示在被觸摸的對象上

試試看:

import UIKit 

class ViewController: UIViewController { 

    var location = CGPoint(x: 0, y: 0)   
    @IBOutlet weak var viewBox: UIView! 
    @IBOutlet weak var cntInViewBox: UILabel! 

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     let touch = touches.first! as UITouch 
     location = touch.locationInView(self.view) 
     viewBox.center = location 
     /*cntInViewBox.text=String(location.x)*/ 
    } 

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     let touch = touches.first! as UITouch 
     location = touch.locationInView(self.view) 
     viewBox.center = location   
     /*cntInViewBox.text=String(location.x)*/ 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     viewBox.center = CGPoint(x:0, y: 0) 
    } 

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

}

沒有線

cntIntViewBox.text=String(location.x) 

它的偉大工程。觸摸屏幕,viewBox跳轉,開始觸摸,框正在移動。

但是,如果我激活線來顯示座標(例如,我的意思是任何動態文本),移動和跳躍不再工作。

爲什麼會出現此問題?

回答

1

問題是你的行改變了標籤的文本。這會導致自動佈局在整個界面中執行。您的viewBox視圖由自動佈局約束定位,因此這些約束將接管並用於定位視圖。約束沒有改變,所以視圖不移動。

+0

哇...完美的答案。我完全理解它。任何解決方案:我可以通過編程禁用自動佈局嗎? – isicom

+0

你真的不需要那樣做。您可以改變其約束,而不是更改視圖的「中心」。但是,如果您真的想完全從自動佈局中刪除這一個視圖,您可以;最簡單的方法是在代碼中而不是在故事板中創建視圖。 – matt

+0

很酷的想法,我會嘗試。感謝馬特;) – isicom

相關問題