kmi*_*las 78 action uibarbuttonitem ios swift
如何设置Swift中自定义UIBarButtonItem的操作?
以下代码成功将按钮放在导航栏中:
var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:nil)
self.navigationItem.rightBarButtonItem = b
Run Code Online (Sandbox Code Playgroud)
现在,我想func sayHello() { println("Hello") }在触摸按钮时打电话.到目前为止我的努力:
var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:sayHello:)
// also with `sayHello` `sayHello()`, and `sayHello():`
Run Code Online (Sandbox Code Playgroud)
和..
var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:@selector(sayHello:))
// also with `sayHello` `sayHello()`, and `sayHello():`
Run Code Online (Sandbox Code Playgroud)
和..
var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:@selector(self.sayHello:))
// also with `self.sayHello` `self.sayHello()`, and `self.sayHello():`
Run Code Online (Sandbox Code Playgroud)
请注意,它sayHello()出现在intellisense中,但不起作用.
谢谢你的帮助.
编辑:对于后代,以下工作:
var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action:"sayHello")
Run Code Online (Sandbox Code Playgroud)
dre*_*wag 147
从Swift 2.2开始,编译器时间检查选择器有一种特殊的语法.它使用语法:#selector(methodName).
Swift 3及更高版本:
var b = UIBarButtonItem(
title: "Continue",
style: .plain,
target: self,
action: #selector(sayHello(sender:))
)
func sayHello(sender: UIBarButtonItem) {
}
Run Code Online (Sandbox Code Playgroud)
如果您不确定方法名称应该是什么样的,那么复制命令的特殊版本非常有用.将光标放在基本方法名称中(例如sayHello)并按 Shift+ Control+ Option+ C.这样就可以粘贴键盘上的"符号名称".如果你也持有Command它将复制"合格的符号名称",其中也包括类型.
Swift 2.3:
var b = UIBarButtonItem(
title: "Continue",
style: .Plain,
target: self,
action: #selector(sayHello(_:))
)
func sayHello(sender: UIBarButtonItem) {
}
Run Code Online (Sandbox Code Playgroud)
这是因为在进行方法调用时,Swift 2.3中不需要第一个参数名称.
您可以在此处了解有关swift.org语法的更多信息:https://swift.org/blog/swift-2-2-new-features/#compile-time-checked-selectors
nor*_*DEV 26
Swift 4的例子
button.action = #selector(buttonClicked(sender:))
@objc func buttonClicked(sender: UIBarButtonItem) {
}
Run Code Online (Sandbox Code Playgroud)
@objc,请参阅下面的示例!#selector(name).private或者public无所谓;你可以使用私人的。override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let menuButtonImage = UIImage(systemName: "flame")
let menuButton = UIBarButtonItem(image: menuButtonImage, style: .plain, target: self, action: #selector(didTapMenuButton))
navigationItem.rightBarButtonItem = menuButton
}
@objc public func didTapMenuButton() {
print("Hello World")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
101561 次 |
| 最近记录: |