Home > Software engineering >  Pass parameters to button action in swift
Pass parameters to button action in swift

Time:12-15

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!

CodePudding user response:

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
}

CodePudding user response:

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
    }
}
  • Related