为select器传递UItapgestureRecognizer的额外参数

我有两个标签,Label1和Label2。 我想做一个单一的函数,打印出哪个标签是通过创buildUITTapRecognizer来为这两个标签调用与传递参数的select器相同的函数。 下面是做这个很混乱,但工作的漫长的道路。 如果我知道如何将一个参数(Int)传递给select器,它将会非常干净。

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") } 

有没有办法来修改select器方法,以便我可以做类似的事情

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

简短的回答:不

这个select器是由UITapGestureRecognizer调用的,你对它传递的参数没有影响。

但是,您可以执行的操作是查询识别器的view属性以获取相同的信息。

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

提供两个手势识别器与采用单个参数的相同select器。 该动作方法将被传递给UIGestureRecognizer实例,并且愉快的是,该手势识别器具有一个名为view的属性,这是gr所附加的视图。

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

我相信一个UITapGestureRecognizer只能用于单个视图。 也就是说,你可以有2个不同的UITapGestureRecognizer调用同一个select器,然后访问函数中的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调用相同的function:

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

如果你试图添加一个UITapGestureRecognizer到两个标签,那么只有最后一个添加的实际上会调用这个函数。