将参数附加到 Swift 中的 button.addTarget 动作 [英] Attach parameter to button.addTarget action in Swift

查看:21
本文介绍了将参数附加到 Swift 中的 button.addTarget 动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个额外的参数传递给 buttonClicked 操作,但无法确定 Swift 中的语法应该是什么.

I am trying to pass an extra parameter to the buttonClicked action, but cannot work out what the syntax should be in Swift.

button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

任何我的 buttonClicked 方法:

Any my buttonClicked method:

func buttonClicked(sender:UIButton)
{
    println("hello")
}

有人有什么想法吗?

感谢您的帮助.

推荐答案

您不能在 addTarget: 中传递自定义参数.另一种选择是设置按钮的 tag 属性和做基于标签的工作.

You cannot pass custom parameters in addTarget:.One alternative is set the tag property of button and do work based on the tag.

button.tag = 5
button.addTarget(self, action: "buttonClicked:", 
    forControlEvents: UIControlEvents.TouchUpInside)

或者对于 Swift 2.2 及更高版本:

Or for Swift 2.2 and greater:

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

这篇关于将参数附加到 Swift 中的 button.addTarget 动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆