2015-09-07 82 views
2

我正在尋找一種方法來查找給定(x,y)座標處UILabel的值(文本)。在Swift中獲取UILabel在座標(x,y)處的值

,其他所有問題似乎是有關獲取標籤的(X,Y),我試圖做相反的事情......

例如(30,40)將返回標籤值在那個位置。

謝謝!

更新

func getLabel(location: CGPoint){ 

    let view = self.view.hitTest(location, withEvent:nil) 
    //I would like to get the value of the label here but I'm not sure how to. 

} 

@IBAction func tap(sender: UITapGestureRecognizer) { 
    var coordinate = sender.locationInView(GraphView?()) 
    getLabel(coordinate) 
} 
+0

不用協調工作,爲什麼不使用標籤? –

+0

查看標題「在視圖中打擊測試」下的UIView文檔。根據所有的子視圖是否爲標籤,你可以使用'hitTest:withEvent:'或'pointInside:withEvent:'。 –

回答

1

您可以通過hit-testing做到這一點。

將您想要的點傳遞給頂層視圖,並且它將返回包含該點的視圖層次結構中最深的視圖。

UIView *view = [self.view hitTest:location withEvent:nil]; 

在斯威夫特,它看起來像

let selectedView = view.hitTest(location, withEvent: nil) 

更新:

您需要設置標籤的userInteractionEnabled爲true,您的標籤註冊命中。

您需要檢查返回的視圖以查看它是否爲標籤,然後檢查它是否有任何文本。

if let label = selectedView as? UILabel 
{ 
    if label.text! 
    { 
     // .. do what you want with the label's text 
    } 
} 
+0

謝謝!你能否告訴我Swift語法看起來如何?我不熟悉obj-c。 – Daniel

+0

'@IBAction FUNC抽頭(發件人:UITapGestureRecognizer){ VAR座標= sender.locationInView(GraphView()?) getLabel(座標) } FUNC getLabel(位置:CGPoint){ 設視圖= self.view。 hitTest(location,withEvent:nil) println(view) println(view.text) }'你能幫忙嗎? – Daniel

+0

您可以編輯您的問題,通過添加您嘗試過的代碼來更新它。還請提及您使用代碼時遇到的問題,以幫助其他讀者解決問題。 – 2015-09-07 16:27:03