2016-07-11 55 views
2

我有兩個標籤Label1和Label2。我想創建一個函數,通過創建UITTapRecognizer來爲兩個標籤調用與傳遞參數的選擇器調用相同函數的方法來打印哪個標籤。下面是這樣做的一個很長的路,這是混亂的,但工作。如果我知道如何將一個參數(Int)傳遞給選擇器,它將會變得更清晰。通過選擇器傳遞UItapgestureRecognizer的額外參數

let topCommentLbl1Tap = UITapGestureRecognizer(target: self, action: #selector(DiscoverCell().doubleTapTopComment1)) 
    topCommentLbl1Tap.numberOfTapsRequired = 2 
    topCommentLbl1.userInteractionEnabled = true 
    topCommentLbl1.addGestureRecognizer(topCommentLbl1Tap) 

let topCommentLbl2Tap = UITapGestureRecognizer(target: self, action: #selector(DiscoverCell().doubleTapTopComment2)) 
     topCommentLbl2Tap.numberOfTapsRequired = 2 
     topCommentLbl2.userInteractionEnabled = true 
     topCommentLbl2.addGestureRecognizer(topCommentLbl2Tap) 

func doubleTapTopComment1() { 
    print("Double Tapped Top Comment 1") 
} 
func doubleTapTopComment2() { 
    print("Double Tapped Top Comment 2") 
} 

是否有修改的選擇方法,這樣我可以做這樣的事情

func doubleTapTopComment(label:Int) { 
    if label == 1 { 
     print("label \(label) double tapped") 
} 

回答

2

簡短的回答道:沒有

的選擇是由UITapGestureRecognizer叫,你有沒有影響它傳遞的參數。

但是,您可以執行的操作是查詢識別器的view屬性以獲取相同的信息。

func doubleTapComment(recognizer: UIGestureRecognizer) { 
    if recognizer.view == label1 { 
     ... 
    } 
    else if recognizer.view == label2 { 
     ... 
    } 
} 
2

提供兩個手勢識別器與採用單個參數的相同選擇器。該動作方法將被傳遞UIGestureRecognizer的實例,並且幸運的是,該手勢識別器具有名爲view的屬性,該屬性是gr所附加的視圖。

... action: #selector(doubleTapTopComment(_:)) 

func doubleTapTopComment(gestureRecognizer: gr) { 
    // gr.view is the label, so you can say gr.view.text, for example 
} 
1

我相信UITapGestureRecognizer只能用於單個視圖。也就是說,你可以有兩個不同的UITapGestureRecognizer s調用相同的選擇器,然後訪問函數中的UITapGestureRecognizer。請看下面的代碼:

import UIKit 

class ViewController: UIViewController { 

    override func viewDidLoad() { 

     super.viewDidLoad() 

     let label1 = UILabel() 
     label1.backgroundColor = UIColor.blueColor() 
     label1.frame = CGRectMake(20, 20, 100, 100) 
     label1.tag = 1 
     label1.userInteractionEnabled = true 
     self.view.addSubview(label1) 

     let label2 = UILabel() 
     label2.backgroundColor = UIColor.orangeColor() 
     label2.frame = CGRectMake(200, 20, 100, 100) 
     label2.tag = 2 
     label2.userInteractionEnabled = true 
     self.view.addSubview(label2) 

     let labelOneTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.whichLabelWasTapped(_:))) 
     let labelTwoTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.whichLabelWasTapped(_:))) 

     label1.addGestureRecognizer(labelOneTap) 
     label2.addGestureRecognizer(labelTwoTap) 

} 

兩個UITapGestureRecognizer稱這相同的功能:

func whichLabelWasTapped(sender : UITapGestureRecognizer) { 
    //print the tag of the clicked view 
    print (sender.view!.tag) 
} 

如果您嘗試添加UITapGestureRecognizer S的一到兩個標籤,則只有最後一個加入將實際調用功能。