如何使用 NSTimer 从 10 秒开始倒计时然后停止计时器?

How do I use NSTimer to countdown from 10 seconds then stop the timer?

这是我目前所拥有的。

 @IBOutlet weak var countLabel1: UILabel!
 @IBOutlet weak var start: UIButton!

 var count = 10

 override func viewDidLoad() {
    super.viewDidLoad()
    var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self.start, selector: Selector("update"), userInfo: nil, repeats: true)
 }

 func update() {
    if(count > 0) {
        countLabel1.text = String(count--)
    } 
 }

 func timerFinished(timer: NSTimer) {
    timer.invalidate()
 }

在您的 class:

中将计时器定义为变量
var timer = NSTimer()

在 viewDidLoad 中创建计时器:

timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: Selector("update"), userInfo: nil, repeats: true)

每 0.4 秒(或多或少)调用一次更新:

func update() {

if(count > 0)
{
    countLabel1.text = String(count--)
} else {
 timer.invalidate()
}}

编辑:[如果您想每秒调用一次更新,当然是输入 1 而不是 0.4。]