xcode 如何将 addTarget 方法更新为 swift 4
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46392832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Update addTarget method to swift 4
提问by Habib Alejalil
when update project code to swift 4 get some error for add.target method how i can fix this error?
当将项目代码更新为 swift 4 时,add.target 方法出现一些错误,我该如何修复此错误?
//swift3
var chatLogController: ChatLogController? {
didSet {
sendButton.addTarget(chatLogController, action: #selector(ChatLogController.handleSend), for: .touchUpInside)
uploadImageView.addGestureRecognizer(UITapGestureRecognizer(target: chatLogController, action: #selector(ChatLogController.handleUploadTap)))
}
}
回答by Rashwan L
The hint message is telling you what to do, add @obj
before declaring your function.
提示消息告诉你要做什么,@obj
在声明你的函数之前添加。
@objc func handleSend(_ sender: UIGestureRecognizer){
...
}
The reason is because:
原因是因为:
In Objective-C, a selector is a type that refers to the name of an Objective-C method. In Swift, Objective-C selectors are represented by the
Selector
structure, and can be constructed using the#selector
expression. To create a selector for a method that can be called from Objective-C, pass the name of the method, such as#selector(MyViewController.tappedButton(_:))
. To construct a selector for a property's Objective-C getter or setter method, pass the property name prefixed by thegetter:
orsetter:
label, such as#selector(getter: MyViewController.myButton)
.
在Objective-C 中,选择器是一种引用Objective-C 方法名称的类型。在 Swift 中,Objective-C 选择器由
Selector
结构表示,并且可以使用#selector
表达式来构造。要为可从 Objective-C 调用的方法创建选择器,请传递该方法的名称,例如#selector(MyViewController.tappedButton(_:))
. 要为属性的 Objective-C getter 或 setter 方法构造选择器,请传递以getter:
或setter:
标签为前缀的属性名称,例如#selector(getter: MyViewController.myButton)
.
Read more here, at Apples documentation.
在此处阅读更多内容,在 Apples 文档中。