xcode 9.0.1/swift 4,没有使用 Objective-C 选择器“onClick:forEvent:"声明的方法 [英] xcode 9.0.1 / swift 4, No method declared with Objective-C selector 'onClick:forEvent:'
问题描述
我使用 swift 4
来构建我的 UI,我创建了一个 UIButton
并想向它添加一个目标.
I use swift 4
to build my UI,I create a UIButton
and want to add a target to it.
但是编译器抛出一个警告:No method created with Objective-C selector 'onClick:forEvent:'
But the complier throw an warning: No method declared with Objective-C selector 'onClick:forEvent:'
button.addTarget(self, action: Selector("onClick:forEvent:"), for: UIControlEvents.touchUpInside)
//...
func onClick(_ sender: Any, forEvent event: UIEvent) {
print("button click", sender, event);
}
当我单击警告三角形时尝试修复此问题.将选择器名称括在括号中以抑制此警告
.
When I click the warning triangle try to fix this.
Wrap the selector name in parentheses to suppress this warning
.
它只是将选择器名称括在括号中.
It just wrap the selector name in parentheses.
button.addTarget(self, action: Selector(("onClick:forEvent:")), for: UIControlEvents.touchUpInside)
构建成功,但是当我单击按钮时.
build success, but when I click the button.
抛出错误
libc++abi.dylib:以 NSException 类型的未捕获异常终止
我知道可以改成#selector(ViewClass.methodName)
和@objc func methodName() {..}
方式.
I know it can be changed to #selector(ViewClass.methodName)
and @objc func methodName() {..}
way.
但是为什么 Selector
不起作用?这是正确的 swift 4
方式吗?
but why Selector
not working ? Is this a correct swift 4
way?
推荐答案
您应该在函数前面加上 @objc
以使其对 Objective-C 运行时可见,例如:
You should prefix the function with @objc
to make it visible to the Objective-C runtime, e.g.:
@objc func onClick(_ sender: Any, forEvent event: UIEvent)
这篇关于xcode 9.0.1/swift 4,没有使用 Objective-C 选择器“onClick:forEvent:"声明的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!