如何在Swift中设置UIBarButtonItem的动作

如何设置Swift中的自定义UIBarButtonItem的操作?

以下代码将button成功放置在导航栏中:

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

现在,当button被触摸时,我想调用func sayHello() { println("Hello") } 。 我迄今的努力:

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

和..

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

和..

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

请注意sayHello()出现在intellisense中,但不起作用。

谢谢你的帮助。

编辑:为了后代,下列作品:

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

从Swift 2.2开始,编译器时间检查select器有一个特殊的语法。 它使用语法: #selector(methodName)

Swift 3:

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

Swift 2.3:

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

这是因为在进行方法调用时,Swift 2.3中不需要第一个参数名称。

你可以在这里了解更多关于swift.org的语法: https ://swift.org/blog/swift-2-2-new-features/#compile-time-checked-selectors