使用后
@IBAction func pauseButton(sender: AnyObject) {
if isPaused == false {
timer.invalidate()
isPaused = true
displayLabel.text = "\(count)"
println("App is paused equals \(isPaused)")
} else if isPaused == true {
var isPaused = false
timer.fire()
// timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
}
要暂停应用程序,我想再次点击暂停,在这种情况下,计时器将从它停止的地方继续计数。
此外,当我按暂停/播放太多次时,会出现多个计时器实例,这将导致计时器每秒增加几次。
请帮忙!
//
// ViewController.swift
// Navigation Bars
//
// Created by Alex Ngounou on 8/27/15.
// Copyright (c) 2015 Alex Ngounou. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var timer = NSTimer()
var count = 0
var isPaused = false
func updateTime() {
switch count {
case 0, 1:
count++
println( "\(count) second.")
displayLabel.text = "\(count)"
case 2:
count++
println("\(count) seconds.")
displayLabel.text = "\(count)"
default:
count++
println("\(count) seconds.")
displayLabel.text = "\(count)"
}
}
**strong text**@IBAction func playButton(sender: AnyObject) {
var isPaused = false
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
@IBAction func stopButton(sender: AnyObject) {
timer.invalidate()
count = 0
displayLabel.text = "0"
}
// if it's currently paused, pressing on the pause button again should restart the counter from where it originally left off.
@IBAction func pauseButton(sender: AnyObject) {
if isPaused == false {
timer.invalidate()
isPaused = true
displayLabel.text = "\(count)"
println("App is paused equals \(isPaused)")
} else if isPaused == true {
var isPaused = false
timer.fire()
// timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
}
@IBAction func resetButton(sender: AnyObject) {
timer.invalidate()
count = 0
displayLabel.text = ""
}
@IBOutlet weak var displayLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最佳答案
Once invalidated, timer objects cannot be reused.
所以本质上,NSTimer
一旦失效就什么都不做。您的 timer
属性必须在该点之后分配给新构造的 NSTimer
对象才能再次触发。如果您的失效簿记准确,则不存在多个计时器的“累积”问题。
不过,可能解决实际问题的最简单方法是逻辑过滤。也就是说,无限期地保持 NSTimer
对象并让它持续触发。当存储的属性 isPaused
为 true
时,您将忽略计时器事件(通过立即从处理函数返回),否则您将处理它们。
关于swift - 在 Swift 中无效后 Timer.fire() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32282415/