在可点击的UIabel中传递参数

时间:2019-01-23 15:36:45

标签: swift uilabel parameter-passing

我正在尝试通过遵循以下代码来制作可点击的UILabel:

let tap_plato = UITapGestureRecognizer(target: self, action: #selector(ViewController.ale_plato1))

plato1.isUserInteractionEnabled = true
plato1.addGestureRecognizer(tap_plato)

...

@objc
func ale_plato1(sender: UITapGestureRecognizer){

let label = sender.view

print ("tapped!")

}

这很好。但是我想将参数传递给函数。像这样:

let tap_plato = UITapGestureRecognizer(target: self, action: #selector(MenuController.ale_plato1("parameter")))
plato1.isUserInteractionEnabled = true
plato1.addGestureRecognizer(tap_plato)


@objc
func ale_plato1(sender: UITapGestureRecognizer, parameterRecived: String){

}

但是我不知道该如何快速处理3 ...

有帮助吗?谢谢

2 个答案:

答案 0 :(得分:1)

无论您使用多个UILabel,将每个标签设置为不同的标签。

for i in 0..<3 {
    let label = UILabel()
    label.tag = i

    let tap = UITapGestureRecognizer(target: self, action: #selector(tap))
    label.isUserInteractionEnabled = true
    label.addGestureRecognizer(tap_plato)
}

@objc func tap(sender: UITapGestureRecognizer) {
    let label = sender.view as! UILabel // if you are SURE that your tap will be a UILabel
    if(label.tag == 0) {
        label.text = "This is label 0"
    if(label.tag == 1) {
        label.text = "This is label 1"
    }
}

轻描淡写,如果有语法问题,请跳过。

在这里,我们可以创建带有标签的标签,然后对它们应用相同的点击。从那里,我们可以检查一下tap方法内的标签,然后从那里进行操作。

答案 1 :(得分:0)

您可以将tag属性用于Int值,但是,如果您需要除此以外的其他功能:

创建一个带有值变量的自定义UILabel类。

class LabelWithValue : UILabel {
    var value : String = ""
}

然后您可以将其用作普通标签

let label = LabelWithValue()
label.text = "bla"
label.value = "Anything"
label.isUserInteractionEnabled = true
label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleGetText)))

然后您可以获取它的文字和价值。

@objc func handleGetText(_ sender : UITapGestureRecognizer) {
    if let label = sender.view as? LabelWithValue {
        print(label.text)
        print(label.value)
    }
}