在Swift中将参数附加到button.addTarget动作
发布于 2021-01-31 23:54:18
我试图将一个额外的参数传递给buttonClicked动作,但是无法计算出Swift中的语法。
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
任何我的buttonClicked方法:
func buttonClicked(sender:UIButton)
{
println("hello")
}
任何想法吗?
谢谢你的帮助。
关注者
0
被浏览
489
1 个回答
-
您无法在中传递自定义参数
addTarget:
。另一种方法是设置tag
button 的属性并根据标签进行工作。button.tag = 5 button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
或对于 Swift 2.2 及更高版本:
button.tag = 5 button.addTarget(self,action:#selector(buttonClicked), forControlEvents:.TouchUpInside)
现在基于
tag
属性做逻辑@objc func buttonClicked(sender:UIButton) { if(sender.tag == 5){ var abc = "argOne" //Do something for tag 5 } print("hello") }