Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach parameter to button.addTarget action in 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)

Any my buttonClicked method:

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

Anyone any ideas?

Thanks for your help.

like image 415
iphaaw Avatar asked Oct 15 '22 07:10

iphaaw


1 Answers

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)

Or for Swift 2.2 and greater:

button.tag = 5
button.addTarget(self,action:#selector(buttonClicked),
    forControlEvents:.TouchUpInside)

Now do logic based on tag property

@objc func buttonClicked(sender:UIButton)
{
    if(sender.tag == 5){

        var abc = "argOne" //Do something for tag 5
    }
    print("hello")
}
like image 189
codester Avatar answered Oct 16 '22 19:10

codester