[英]Handle the selector parameter in swift
Let's say I declare a function in my CustomTimer class: 假设我在CustomTimer类中声明了一个函数:
class CustomTimer {
class func scheduledTimerWithSelector(aSelector: Selector) -> CustomTimer {
// aSelector ??
}
}
How can I handle this aSelector parameter? 如何处理此aSelector参数?
Like the NSTimer.scheduledTimerWithTimeInterval method, how dose it work? 像NSTimer.scheduledTimerWithTimeInterval方法一样,它如何工作?
You should check the Selector
structure. 您应该检查Selector
结构。 From the apple docs: 从苹果文档:
In Swift, Objective-C selectors are represented by the Selector structure. 在Swift中,Objective-C选择器由Selector结构表示。 You can construct a selector with a string literal, such as let mySelector: Selector = "tappedButton:". 您可以使用字符串文字构造选择器,例如let mySelector:Selector =“ tappedButton:”。 Because string literals can be automatically converted to selectors, you can pass a string literal to any method that accepts a selector. 由于字符串文字可以自动转换为选择器,因此您可以将字符串文字传递给任何接受选择器的方法。
Selector function with Swift : Swift的选择器功能:
func selectorFunc(aSel:Selector){
if self.respondsToSelector(aSel){
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: aSel, userInfo: nil, repeats: false)
}
}
func gooleIt(){
println("Hello")
}
Function Call : 函数调用:
self.selectorFunc(Selector(gooleIt()))
Hope it help you. 希望对您有帮助。
You can declare a method with a selector like this and you can call it by creating a UIControl because performSelector methods are not available in Swift: 您可以使用这样的选择器声明一个方法,并且可以通过创建UIControl来调用它,因为performSelector方法在Swift中不可用:
func methodWithSelector(sel:Selector) {
var control = UIControl()
control.sendAction(sel, to: self, forEvent: nil)
}
If you do not need to call it on the main thread another option is like this: 如果您不需要在主线程上调用它,则另一个选择是这样的:
func methodWithSelector(sel:Selector) {
NSThread.detachNewThreadSelector(sel, toTarget: self, withObject: nil)
}
You will call it like this: 您将这样称呼它:
methodWithSelector(Selector("methodCall"))
or like this 或像这样
methodWithSelector("methodCall")
then you must have a method with the name of the selector 那么您必须有一个带有选择器名称的方法
func methodCall() {
println("methodCall")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.