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.