ios Swift - 如何在带参数的方法上调用 Selector()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24467500/
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
Swift - How to call Selector() on method with arguments?
提问by Kosmetika
I'm learning Swift and need to call my method on tap, here is the code:
我正在学习 Swift,需要随时调用我的方法,这是代码:
var gestureRecognizer = UITapGestureRecognizer()
myView.addGestureRecognizer(gestureRecognizer)
gestureRecognizer.addTarget(self, action: Selector(dismiss(nil)))
This returns error - Could not find an overload for init that accepts the supplied arguments
这将返回错误 - Could not find an overload for init that accepts the supplied arguments
I also tried like Selector("dismiss:nil")
and Selector("dismiss(nil)")
with no luck..
我也试过喜欢Selector("dismiss:nil")
和Selector("dismiss(nil)")
没有运气好的话..
Here the method I'm calling:
这是我正在调用的方法:
func dismiss(completion: (() -> Void)!) {
self.dismissViewControllerAnimated(true, completion: completion)
}
回答by dasdom
Just use the name of the method as a string:
只需使用方法的名称作为字符串:
gestureRecognizer.addTarget(self, action: "dismiss:")
Edit: In Swift 3.0 you will have to use the following syntax:
编辑:在 Swift 3.0 中,您必须使用以下语法:
gestureRecognizer.addTarget(self, action: #selector(dismiss(_:)))
回答by Mick MacCallum
You don't pass arguments in selectors. You only represent that there is one with a colon. Additionally, you don't have to use the Selector type at all. If you pass in a String literal, it is converted to a Selector for you.
您不在选择器中传递参数。你只表示有一个带冒号的。此外,您根本不必使用 Selector 类型。如果您传入一个字符串文字,它会为您转换为一个 Selector。
gestureRecognizer.addTarget(self, action:"dismiss:")