5

please anyone tell me, How to send additional parameter in addtarget function in swift 2.2? Example:

button.addTarget(self, action: #selector(classname.myFunc(_:)), forControlEvents: UIControlEvents.TouchUpInside))

func myFunc(sender:UIButton){
    print(“i am here“)
}

to

func myFunc(sender:UIButton,parameter:String){
    print(“i am here“)
}
sulabh qg
  • 1,155
  • 2
  • 12
  • 20
  • Possible duplicate of [Attach parameter to button.addTarget action in Swift](http://stackoverflow.com/questions/24814646/attach-parameter-to-button-addtarget-action-in-swift) – KTPatel Dec 22 '16 at 09:44

5 Answers5

3

You can create a subclass of UIButton, add one property named parameter which you want to pass as an extra parameter.

In addTarget(), you can only choose passing the caller or not. In this case, the caller is a UIButton.

So use the subclass and call addTarget(), then you can get the string which you want send:

func myFunc(sender: customUIButton) {
    // do something with sender.parameter
}

Hope it can help you.

merito
  • 465
  • 4
  • 15
2

In Swift 2.2 you can do something like this.

myUISlider.addTarget(self, action:#selector(self.onSliderValChanged(_:withEvent:)), forControlEvents: .ValueChanged)

func onSliderValChanged(slider: UISlider, withEvent event: UIEvent?) {
    }
Hanny
  • 1,322
  • 15
  • 20
2

I use sender properties to send some parameters with it like

button.accessibilityHint = "param 1"
button.accessibilityValue = "param 2"
button.tag = 0

button.addTarget(self, action: #selector(buttonPressed(_:)),   forControlEvents: UIControlEvents.TouchUpInside))

func myFunc(sender:UIButton){

 print(sender.accessibilityHint) // param1
 print(sender.accessibilityValue) // param2
 print(sender.tag) // 0

}
0

It's not possible. You have to use a workaround.

button.addTarget(self, action: #selector(classname.myFunc(_:)), forControlEvents: UIControlEvents.TouchUpInside))

func myFunc(sender:UIButton){
    self.myFunc2(sender, parameter: "My parameter")
}

func myFunc2(sender:UIButton,parameter:String){
}
Code
  • 6,041
  • 4
  • 35
  • 75
  • 1
    This wont solve the issue unless the parameter is a global varibale. If that was the case then we didnt need to pass the parameter itself. Selector can only provide the caller as sender. Nothing more. – kandelvijaya Jun 16 '16 at 09:57
  • @kandelvijaya What issue are you referring to? OP didn't mention any. Anyway, it's possible OP wants to call `myFunc2` with string X when button1 is tapped, and `myFunc2` with string Y when button2 is tapped. So there is nothing wrong with this design. – Code Jun 16 '16 at 10:12
0

Swift 5.0 code

theButton.addTarget(self, action: #selector(theFunc), for: .touchUpInside) 
theButton.frame.name = "myParameter"

.

@objc func theFunc(sender:UIButton){ 
print(sender.frame.name)
}
gorimali
  • 33
  • 1
  • 4