2015-06-22 36 views
7

我有一個按鈕叫,我給了它一個UIGestureRecognizer,以便IBAction只在長按按鈕時運行。您可以通過將UILongPressGestureRecognizer添加到按鈕iteself來完成此操作。然後,您可以控制手勢識別拖到這樣的功能:UITapGestureRecognizer發件人是手勢,而不是UI對象

@IBAction func handleGesture(sender: UIGestureRecognizer) { 
    if sender.state == UIGestureRecognizerState.Began 
    { 
     let labelTap1=UITapGestureRecognizer(target: self, action: "labelTapped:") 
     let alertController = UIAlertController(title: "**I want this to be the title of the button**", message: 
      "This is the description of the function you pressed", preferredStyle: UIAlertControllerStyle.Alert) 
     alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil)) 

     self.presentViewController(alertController, animated: true, completion: nil) 
    } 
} 

正如你可以看到UIAlertController出現,我想這個標題上顯示的按鈕當前標題。如果這個函數的發送者是按鈕,我可以用sender.currentTitle調用它。當函數的發件人是手勢時,如何獲取與手勢相關聯的按鈕的標題。

我已經在目標C中看到類似這樣的帖子,但沒有真正在Swift上。這是一個項目,當你長按按鈕本身時,就可以獲得按鈕描述。如果任何人有任何想法如何用我迄今爲止所做的或者有不同的方法來實現這一點,請告訴我。

謝謝!

回答

14

您可以通過其視圖屬性獲取手勢添加到的視圖的引用。在這種情況下,您將其添加到按鈕,以便視圖屬性將返回給您您按鈕。

let button = sender.view as? UIButton 
+0

啊,這很有道理。我是來自前端Web背景的新手,而且是iOS。謝謝您的幫助! – modesitt

+0

是的,實際上跟你說話的是手勢識別器;這是代理人發現的行動。然後,您需要詢問它正在觀看哪個視圖。不知道這是否有幫助。 – Tommy

相關問題