Reputation: 325
When setting the action with the "addTarget" method on a button in Swift, is there a way for me to pass a parameter to the function I want to trigger? Say I had a simple scenario like this:
let button = UIButton()
button.addTarget(self, action: #selector(didPressButton), for: .touchUpInside)
@objc func didPressButton() {
// do something
}
Obviously the above code works fine, but say I wanted the 'didPressButton' function to take in a parameter:
@objc func didPressButton(myParam: String) {
// do something with myParam
}
Is there a way I can pass a parameter into the function in the 'addTarget' method? Something like this:
let button = UIButton()
button.addTarget(self, action: #selector(didPressButton(myParam: "Test")), for: .touchUpInside)
@objc func didPressButton(myParam: String) {
// do something with myParam
}
I'm coming from a JavaScript background and in JavaScript it's pretty simple to achieve this behavior by simply passing an anonymous function that would then call the 'didPressButton' function. However, I can't quite figure how to achieve this with swift. Can a similar technique be used by using a closure? Or does the '#selector' keyword prevent me from doing something like that?
Thank you to anyone who can help!
Upvotes: 1
Views: 2480
Reputation: 34
Well in my case I needed to pass one UIlabel text as a parameter, so I added a button over it. Set its textlabel as the UIlabel. Catch that in selector by casting the sender into UIButton and then retrieving the textLabel.
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, bottomheight, CGRectGetWidth(bottomview.frame), note.frame.size.height)];
btn.titleLabel.text = note.text;
[btn addTarget:[self.view parentFocusEnvironment] action:@selector(showDispatcherNote:) forControlEvents:UIControlEventTouchUpInside];
--------selector method-----------------
UIButton *btn = (UIButton *)sender;
NSString * text = btn.titleLabel.text;
Upvotes: -1
Reputation: 232
It is not possible to do that in iOS. You can get the View in the selector in your case it is a button.
button.addTarget(self, action: #selector(buttonClick(_:)), for: .touchUpInside)
@objc func buttonClick(_ view: UIButton) {
switch view.titleLabel?.text {
case "Button":
break
default:
break
}
}
Upvotes: 0
Reputation: 3045
The short answer is no.
The target selector mechanism only sends the target in the parameters. If the string was a part of a subclass of UIbutton then you could grab it from there.
class SomeButton: UIButton {
var someString: String
}
@objc func didPressButton(_ button: SomeButton) {
// use button.someString
}
Upvotes: 1