Cómo configurar la acción para un UIBarButtonItem en Swift


¿Cómo se puede configurar la acción para un UIBarButtonItem personalizado en Swift?

El siguiente código coloca correctamente el botón en la barra de navegación:

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:nil)
self.navigationItem.rightBarButtonItem = b

Ahora, me gustaría llamar a func sayHello() { println("Hello") } cuando se toque el botón. Mis esfuerzos hasta ahora:

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:sayHello:)
// also with `sayHello` `sayHello()`, and `sayHello():`

Y..

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:@selector(sayHello:))
// also with `sayHello` `sayHello()`, and `sayHello():`

Y..

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:@selector(self.sayHello:))
// also with `self.sayHello` `self.sayHello()`, and `self.sayHello():`

Tenga en cuenta que sayHello() aparece en intellisense, pero no funciona.

Gracias por su ayuda.

EDITAR: Para la posteridad, las siguientes obras:

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:"sayHello")
Author: HpTerm, 2014-07-09

2 answers

A partir de Swift 2.2, hay una sintaxis especial para los selectores controlados en tiempo de compilador. Utiliza la sintaxis: #selector(methodName).

Swift 3 y posteriores:

var b = UIBarButtonItem(
    title: "Continue",
    style: .plain,
    target: self,
    action: #selector(sayHello(sender:))
)

func sayHello(sender: UIBarButtonItem) {
}

Si no está seguro de cómo debería ser el nombre del método, hay una versión especial del comando copiar que es muy útil. Coloque el cursor en algún lugar del nombre del método base (por ejemplo, sayHello) y presione Shift+Control+Opción+C. Que pone el 'Nombre del símbolo' en su teclado para ser pegada. Si también mantiene Comando copiará el 'Nombre del Símbolo calificado' que incluirá el tipo también.

Swift 2.3:

var b = UIBarButtonItem(
    title: "Continue",
    style: .Plain,
    target: self,
    action: #selector(sayHello(_:))
)

func sayHello(sender: UIBarButtonItem) {
}

Esto se debe a que el nombre del primer parámetro no es necesario en Swift 2.3 cuando se hace una llamada a un método.

Puede obtener más información sobre la sintaxis en swift.org aquí: https://swift.org/blog/swift-2-2-new-features/#compile-time-checked-selectors

 135
Author: drewag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-10 05:27:34

Ejemplo de Swift 4

button.action = #selector(buttonClicked(sender:))

@objc func buttonClicked(sender: UIBarButtonItem) {

}
 2
Author: norbDEV,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-06 09:00:39