Parameter step with Target - Action

0

I have a button to which I have added a Target so that when it is clicked I call a function. I need to pass through the target an extra parameter that is not the button but I throw error when trying to compile

If I just pass the button it lets me compile in this way:

Example:

//... codigo

let selector = #selector(self.selectButton(_:))
button.addTarget(self, action: selector, for: .touchUpInside)

//... mas codigo    

func selectButton(_ sender: UIButton) {
 // Codigo que se ejecuta cuando pulso boton
}

Example that fails:

//... codigo

let selector = #selector(self.selectButton(sender: button, parametro: miObjeto))
button.addTarget(self, action: selector, for: .touchUpInside)

//... mas codigo    

func selectButton(sender: UIButton, parametro: Objeto) {
 // Codigo que se ejecuta cuando pulso boton
}
    
asked by Popularfan 09.02.2018 в 13:57
source

1 answer

1

Short answer: You can not

Explanation: At the moment of adding a #selector to a UIButton , the compiler is being told that we want the function " passed " (1) to be executed by means of this selector. This forces the signing of the function to be one of the signatures declared in UIControl , one of them is the one you used:

func selectButton(_ sender: UIButton) {
// Codigo que se ejecuta cuando pulso boton
}

Where sender is the object that sends the message.

If we add parameters to the function, it stops complying with the signature (and with all of UIControl ). That's why you see the compilation error.

Possible solutions: It depends a lot on what you want to achieve, but one option is to create an Enumeration that represents the different cases that can happen when you press a button, for example:

enum AccionBotón {
    case actualizar
    case borrar
    case crear
}

In the UIViewController you save a variable of type AccionBotón (which I will call acción ). The selector (or IBAction ) of the button would look like this:

func selectButton(_ sender: UIButton) {
    switch self.acción {
    case .actualizar:
         //actualizar
    case .borrar:
         //borrar
    case .crear
         //crear
    }
}

Another option is to create a dictionary of options, for example:

var nada = [
    1 : ["a" : "a"],
    2 : ["b" : "b"],
    3 : ["c" : "c"]
]

And in the selector (or IBAction ) of the button:

let opción = nada[2] //falta un if o algo que decida si queremos 1,2 o 3

Whatever option you choose, you will have to save all the possible "parameters" somewhere (either in the same UIViewController or elsewhere) and a way to know which of those "parameters" to choose in the selector of the button.

(1) The function does not really "pass", it is resolved at runtime, in fact, in the first versions of Swift, the compiler did not force the selectors to coincide with the signature of the functions. If it did not match, the application closed with an error.

    
answered by 12.02.2018 в 18:45