如何将多个参数传递给选择器函数

How to pass multiple parameters to selector function

我有一个子视图,它有一个选择器

let subView1: CustomSubView = CustomSubView(frame: CGRect(x: 0, y: 0 , width: xx, height: yy))

    subView1.label.text = "Lorem Ipsum"
    cell.scroller.addSubview(subView1)
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.subView1Action(_:)))
    subView1.addGestureRecognizer(gesture)

func subView1Action(sender:UITapGestureRecognizer){
        print("Wow Subview1 is clicked")
    }

现在,我想将标签文本发送到选择器函数。我该怎么做? 如果我让选择器函数像:

func subView1Action(sender:UITapGestureRecognizer , label:String){
        print(label)
    }

我应该怎么称呼它?

您不能更改委托回调签名。

但对于您的情况,您可以使用 sender.view 取回 UILabel。

func subView1Action(sender:UITapGestureRecognizer){
    if let label = sender.view as? UILabel {
        print(label.text)
    }
}

你误会了。 将 UITapGestureRecognizer 设置为选择器时,识别器对象将仅使用 "sender" 调用选择器。所以基本上你什么也不能加。

如果字符串是点击视图的 属性,您将可以从识别器访问它,否则您将不得不以其他方式传递它。

func someAction(sender:UITapGestureRecognizer){
    if let label = sender.view as? UILabel {
        print(label)
    }
}

只需将 UITapGestureRecognizer 设置为唯一的函数参数。然后您可以使用 sender.view as? UILabel.

访问标签