我试图在Swift中创建一个NSTimer,但我遇到了一些麻烦。

NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)

Test()是同一个类中的一个函数。


我在编辑器中得到一个错误:

无法找到一个超载的'init'接受提供的 参数

当我把selector: test()改为selector: nil时,错误就消失了。

我试过了:

选择器:测试() 选择器:测试 选择器:选择器(测试())

但是什么都没用,我在参考文献中找不到解决方案。


当前回答

Swift 3

//创建定时器的示例代码

Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)

WHERE
timeInterval:- Interval in which timer should fire like 1s, 10s, 100s etc. [Its value is in secs]
target:- function which pointed to class. So here I am pointing to current class.
selector:- function that will execute when timer fires.

func updateTimer(){
    //Implemetation 
} 

repeats:- true/false specifies that timer should call again n again.

其他回答

同样,如果你的(Swift)类不是来自Objective-C类,那么你必须在目标方法名称字符串的末尾有一个冒号,你必须使用@objc属性与你的目标方法,例如。

var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))

@objc func method() {
    // Something cool here   
} 

否则你会在运行时得到一个“unrecognized Selector”错误。

创建如下所示的选择器。 1.

UIBarButtonItem(
    title: "Some Title",
    style: UIBarButtonItemStyle.Done,
    target: self,
    action: "flatButtonPressed"
)

2.

flatButton.addTarget(self, action: "flatButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)

注意,@selector语法消失了,取而代之的是一个简单的String来命名要调用的方法。有一个方面,我们都同意冗长是一个障碍。当然,如果我们声明有一个名为flatButtonPressed的目标方法:我们最好写一个:

func flatButtonPressed(sender: AnyObject) {
  NSLog("flatButtonPressed")
}

设置定时器:

    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
                    target: self, 
                    selector: Selector("flatButtonPressed"), 
                    userInfo: userInfo, 
                    repeats: true)
    let mainLoop = NSRunLoop.mainRunLoop()  //1
    mainLoop.addTimer(timer, forMode: NSDefaultRunLoopMode) //2 this two line is optinal

为了完整,这里是flatButtonPressed

func flatButtonPressed(timer: NSTimer) {
}

Swift 3

//创建定时器的示例代码

Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)

WHERE
timeInterval:- Interval in which timer should fire like 1s, 10s, 100s etc. [Its value is in secs]
target:- function which pointed to class. So here I am pointing to current class.
selector:- function that will execute when timer fires.

func updateTimer(){
    //Implemetation 
} 

repeats:- true/false specifies that timer should call again n again.

我发现很多答案都很有用,但我不清楚如何用一个不是按钮的东西来做到这一点。我在swift中添加了一个手势识别器到UILabel中,所以在阅读以上所有内容后,我发现以下是对我有用的:

let tapRecognizer = UITapGestureRecognizer(
            target: self,
            action: "labelTapped:")

其中“Selector”被声明为:

func labelTapped(sender: UILabel) { }

请注意,它是公共的,我没有使用Selector()语法,但也可以这样做。

let tapRecognizer = UITapGestureRecognizer(
            target: self,
            action: Selector("labelTapped:"))

正如许多人所说,选择器是一种动态调用方法的objective - c方式,已经被带到了Swift中,在某些情况下我们仍然坚持使用它,比如UIKit,可能是因为他们在SwiftUI上工作来取代它,但一些api有更Swift的版本,比如Swift Timer,例如你可以使用

class func scheduledTimer(withTimeInterval interval: TimeInterval, 
                                            repeats: Bool, 
                                              block: @escaping (Timer) -> Void) -> Timer

相反,你可以这样称呼它

Timer.scheduledTimer(withTimeInterval: 1, 
                              repeats: true ) {
    ... your test code here
}

or

Timer.scheduledTimer(withTimeInterval: 1, 
                              repeats: true,
                              block: test)

方法test需要一个Timer参数,或者如果你想test需要一个命名参数

Timer.scheduledTimer(withTimeInterval: 1, 
                              repeats: true,
                              block: test(timer:))

你也应该使用Timer而不是NSTimer因为NSTimer是objective-c的旧名字