skip to Main Content

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!

2

Answers


  1. 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
    }
    
    Login or Signup to reply.
  2. 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
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search