使用选择器为 UItapgestureRecognizer 传递额外的参数

use*_*902 4 selector ios swift

我有两个标签,Label1 和 Label2。我想创建一个函数,通过为两个标签创建 UITTapRecognizer,使用传递参数的选择器调用相同的函数来打印出哪个标签被点击。下面是很长的路要走,虽然杂乱但有效。如果我知道如何将参数 (Int) 传递给选择器,它会更清晰。

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")
}
Run Code Online (Sandbox Code Playgroud)

有没有办法修改选择器方法,这样我就可以做类似的事情

func doubleTapTopComment(label:Int) {
    if label == 1 {
        print("label \(label) double tapped")
}
Run Code Online (Sandbox Code Playgroud)

Avi*_*Avi 6

简短回答:没有

选择器由 调用UITapGestureRecognizer,您对它传递的参数没有影响。

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

func doubleTapComment(recognizer: UIGestureRecognizer) {
    if recognizer.view == label1 {
        ...
    }
    else if recognizer.view == label2 {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)