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.
In Swift 3 make a selector like that:
And catch the event like that:
I appreciate everyone saying use tags, but really you need to extend the UIButton class and simply add the object there..
Tags are a hopeless way round this. Extend the UIButton like this (in Swift 4)
then your call may be call (NOTE THE colon ":" in
Selector(("webButtonTouched:"))
)then finally catch it all here
You do this one time and use it throughout your project (you can even make the child class have a generic "object" and put whatever you like into the button!). Or use the example above to put an inexhaustible number of key/string params into the button.. Really useful for including things like urls, confirm message methodology etc
As an aside, it's important that the
SO
community realise this there is an entire generation of bad practice being cut'n'paste round the internet by an alarming number of programmers who don't understand/haven't been taught/missed the point of the concept ofobject extensions
For Swift 3.0 you can use following
For Swift 2.X and above
If you want to send additional parameters to the buttonClicked method, for example an indexPath or urlString, you can subclass the UIButton:
Make sure to change the button's class in the identity inspector to subclassedUIButton. You can access the parameters inside the buttonClicked method using
sender.indexPath
orsender.urlString
.Note: If your button is inside a cell you can set the value of these additional parameters in the cellForRowAtIndexPath method (where the button is created).
If you have a loop of buttons like me you can try something like this