This question already has answers here:
Why would a `scheduledTimer` fire properly when setup outside a block, but not within a block?

(3个答案)


4年前关闭。




我一直在尝试在Swift中使用Timer,并将其简化为以下内容:
func startTimer () {
    timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.test), userInfo: nil, repeats: true)
}
func test () {
    print("FIRED")
}

我想从另一个函数调用此函数,并已验证startTimer函数可以正常工作,但计时器不会触发。这与RunLoop有关吗?我对编码还很陌生,因此不胜感激。

最佳答案

优良作法:在startTimer()中,检查尚未创建的计时器并进行分配。在stopTimer()中,在调用invalidate之前检查计时器是否存在,然后将计时器设置回nil。

另外,对于选择器,请确保您具有@objc前缀。您应该能够使用提供的代码获得一个工作计时器。祝您编码愉快!

class SomeClass {
    var timer: Timer?

    func startTimer() {
        guard timer == nil else { return }
        timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(test), userInfo: nil, repeats: true)
    }

    func stopTimer() {
        guard timer != nil else { return }
        timer?.invalidate()
        timer = nil
    }

    @objc func test() {

    }
}

关于ios - Swift 3计时器未触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41306866/

10-11 15:33
查看更多