简体   繁体   中英

How to send additional parameter in addtarget function?

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

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.

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?) {
    }

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

}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM