简体   繁体   English

将参数传递给选择器指向的函数

[英]pass parameter to selector pointed function

I am programming with Swift 2.1. 我正在使用Swift 2.1进行编程。

I have a function in class: 我在课堂上有一个职能:

private func doTask(button: UIButton) {...}

I want to call this function after 2 seconds, I know I could use : 我想在2秒后调用此函数,我知道我可以使用:

NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "doTask", userInfo: nil, repeats: false)

But, in the selector part, how can I pass the parameter button: UIButton to doTask ? 但是,在selector部分中,如何将参数button: UIButton传递给doTask

Timers can only call methods that take a timer as their parameter. 计时器只能调用以计时器为参数的方法。 Selectors are just names of methods; 选择器只是方法的名称; they can't carry data. 他们无法携带数据。 You have to make a new method that takes a timer and calls doTask . 您必须创建一个新方法,该方法需要一个计时器并调用doTask You can pass data in the userInfo parameter if you want to configure things, but you still need an extra method. 如果要配置内容,可以在userInfo参数中传递数据,但仍然需要其他方法。

This kind of timer probably isn't what you want anyway. 无论如何,这种计时器可能不是您想要的。 Just use dispatch_after . 只需使用dispatch_after

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    doTask(button)
}

You can see Matt's implementation of delay() that makes this a little easier to use. 您可以看到Matt的delay() ,使它更易于使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM