如何在0. Swift停止计时器倒计时

Mil*_* H. 0 xcode swift

有没有人知道我怎么能告诉计时器在它达到0时停止.现在它继续倒数到零以下.

import UIKit

class ViewController: UIViewController {
    var timerCount = 20
    var timerRunning = false
    var timer = NSTimer()

    @IBOutlet weak var timerLabel: UILabel!

    func Counting() {
        timerCount -= 1
        timerLabel.text = "\(timerCount)"
    }

    @IBAction func startButton(sender: UIButton) {
        if timerRunning == false {
            timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector ("Counting"), userInfo: nil, repeats: true)
            timerRunning = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if timerCount == 0 {
            timerRunning = false
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ahr*_*uss 5

将您的Counting功能更改为:

func Counting() {
    timerCount -= 1
    timerLabel.text = "\(timerCount)"
    if timerCount == 0 {
        timer.invalidate()
        timerRunning = false
    }
}
Run Code Online (Sandbox Code Playgroud)

NSTimer文档:

停止计时器

invalidate()

阻止接收器再次发射并请求将其从运行循环中移除.

讨论

此方法是从NSRunLoop对象中删除计时器的唯一方法.NSRunLoop对象在invalidate方法返回之前或稍后的某个时间点删除其对计时器的强引用.

如果它配置了目标和用户信息对象,则接收器也会删除对这些对象的强引用.

特别注意事项

您必须从安装了计时器的线程发送此消息.如果从另一个线程发送此消息,则可能无法从其运行循环中删除与计时器关联的输入源,这可能会阻止线程正常退出.