在 iOS 中暂停和恢复计时器 [英] Pausing and Resuming a Timer in iOS
问题描述
这是一个常见问题,但大多数答案似乎都不起作用.我的应用程序中有一个计时器,我可以轻松启动和重新启动计时器.我正在尝试暂停和恢复计时器,但现在恢复只会从比我恢复它的计时器更大的计时器继续计时器.这可能意味着它会在后台继续计数.这是我的代码:
//定时器变量var startTime = NSTimeInterval()var timer = NSTimer()var isTiming = Bool()var isPaused = Bool()功能更新定时器(){让 currentTime = NSDate.timeIntervalSinceReferenceDate()var elapsedTime: NSTimeInterval = currentTime - startTime让分钟 = UInt8(elapsedTime/60.0)elapsedTime -= (NSTimeInterval(minutes) * 60)让秒 = UInt8(elapsedTime)elapsedTime -= NSTimeInterval(seconds)让 strMinutes = String(格式: "%02d", 分钟)让 strSeconds = String(格式: "%02d", 秒)锻炼时间.文本 = "(strMinutes) : (strSeconds)"}@IBAction func startButtonTapped(sender: AnyObject) {如果 !timer.valid {timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)startTime = NSDate.timeIntervalSinceReferenceDate()}isTiming = 真isPaused = 假}@IBAction func pauseAndContinueButtonTapped(sender: AnyObject) {if isTiming == true &&isPaused == false {timer.invalidate()//停止定时器isPaused = true//isPausedisTiming = false//停止计时pauseButton.setTitle("RESUME", forState: UIControlState.Normal)//设置按钮继续状态打印(开始时间)} else if isTiming == false &&isPaused == true {如果 !timer.valid {timer.invalidate()//计时器=零timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)}isPaused = 假isTiming = 真pauseButton.setTitle("PAUSE", forState: UIControlState.Normal)//设置按钮继续状态}}
我有一个自定义计时器应用程序并处理了相同的问题.有很多方法可以解决这个问题.您可能想像跟踪 elapsedTime
一样跟踪 pausedTime
并从其他变量中减去它.这也为您提供了一些灵活性,可以显示 totalTime
与 elapsedTime
等...我的功能有点不同,所以我将它改装到您的设置中.>
基本上,暂停是不同的,因为您可以多次暂停/恢复.因此,您需要跟踪之前的暂停和当前的暂停状态,并从经过的时间(或总时间,或任何您想要的时间)中减去.
我测试了这段代码,它奏效了.试试看,让我知道:
导入 UIKit类 TimedWorkoutViewController: UIViewController {@IBOutlet 弱变量 pauseButton:UIButton!@IBOutlet 弱变量 startButton:UIButton!var startTime = NSTimeInterval()var timer = NSTimer()var isTiming = Bool()var isPaused = Bool()var pausedTime: NSDate?//跟踪当前暂停开始的时间var pausedIntervals = [NSTimeInterval]()//跟踪之前的暂停覆盖 func viewDidLoad() {super.viewDidLoad()}功能更新定时器(){让 currentTime = NSDate.timeIntervalSinceReferenceDate()var pausedSeconds = pausedIntervals.reduce(0) { $0 + $1 }//计算定时器之前暂停的总时间如果让 pausedTime = pausedTime {pausedSeconds += NSDate().timeIntervalSinceDate(pausedTime)//如果暂停则添加当前暂停}var elapsedTime: NSTimeInterval = currentTime - startTime - pausedSeconds//减去暂停时间让分钟 = Int(elapsedTime/60.0)elapsedTime -= (NSTimeInterval(minutes) * 60)让秒 = Int(elapsedTime)elapsedTime -= NSTimeInterval(seconds)让 strMinutes = String(格式: "%02d", 分钟)让 strSeconds = String(格式: "%02d", 秒)锻炼时间.文本 = "(strMinutes) : (strSeconds)"}@IBAction func startButtonTapped(sender: AnyObject) {如果 !timer.valid {timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)startTime = NSDate.timeIntervalSinceReferenceDate()}isTiming = 真isPaused = 假pausedIntervals = []//在新的锻炼中重置 pausedTimeCollector}@IBAction func pauseAndContinueButtonTapped(sender: AnyObject) {if isTiming == true &&isPaused == false {timer.invalidate()//停止定时器isPaused = true//isPausedisTiming = false//停止计时pausedTime = NSDate()//假设您正在启动一个全新的锻炼计时器pauseButton.setTitle("RESUME", forState: UIControlState.Normal)//设置按钮继续状态} else if isTiming == false &&isPaused == true {let pausedSeconds = NSDate().timeIntervalSinceDate(pausedTime!)//获取暂停时间pausedIntervals.append(pausedSeconds)//添加到暂停时间收集器pausedTime = nil//清除当前暂停状态如果 !timer.valid {timer.invalidate()//计时器=零timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)}isPaused = 假isTiming = 真pauseButton.setTitle("PAUSE", forState: UIControlState.Normal)//设置按钮继续状态}}}
This is a bit of a common question but most answers don't seem to work. I have a timer in my app that and I can start and re-start the timer easily. I am trying to pause and resume the timer but for now resuming only continues the timer from a timer that's greater than the one I resumed it at. Which probably means it continues counting in the background. This is my code :
//Timer Variables
var startTime = NSTimeInterval()
var timer = NSTimer()
var isTiming = Bool()
var isPaused = Bool()
func updatedTimer() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var elapsedTime: NSTimeInterval = currentTime - startTime
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
workoutTime.text = "(strMinutes) : (strSeconds)"
}
@IBAction func startButtonTapped(sender: AnyObject) {
if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
isTiming = true
isPaused = false
}
@IBAction func pauseAndContinueButtonTapped(sender: AnyObject) {
if isTiming == true && isPaused == false {
timer.invalidate() //Stop the Timer
isPaused = true //isPaused
isTiming = false //Stopped Timing
pauseButton.setTitle("RESUME", forState: UIControlState.Normal) //Set Button to Continue state
print(startTime)
} else if isTiming == false && isPaused == true {
if !timer.valid {
timer.invalidate()
//timer = nil
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
}
isPaused = false
isTiming = true
pauseButton.setTitle("PAUSE", forState: UIControlState.Normal) //Set Button to Continue state
}
}
I have a custom timer application and dealt with the same issue. There are many ways to address this. You may want to track pausedTime
like you do elapsedTime
and subtract that from your other variables. This gives you some flexibility as well to show totalTime
vs. elapsedTime
, etc... My function is quite a bit different, so I retrofitted it to your setup.
Basically, pausing is different because you can pause/resume multiple times. So you need to track previous pauses, and current pause state and subtract from elapsed time (or total time, or whatever you want).
I tested this code and it worked. Give it a try and let me know:
import UIKit
class TimedWorkoutViewController: UIViewController {
@IBOutlet weak var pauseButton: UIButton!
@IBOutlet weak var startButton: UIButton!
var startTime = NSTimeInterval()
var timer = NSTimer()
var isTiming = Bool()
var isPaused = Bool()
var pausedTime: NSDate? //track the time current pause started
var pausedIntervals = [NSTimeInterval]() //track previous pauses
override func viewDidLoad() {
super.viewDidLoad()
}
func updatedTimer() {
let currentTime = NSDate.timeIntervalSinceReferenceDate()
var pausedSeconds = pausedIntervals.reduce(0) { $0 + $1 } //calculate total time timer was previously paused
if let pausedTime = pausedTime {
pausedSeconds += NSDate().timeIntervalSinceDate(pausedTime) //add current pause if paused
}
var elapsedTime: NSTimeInterval = currentTime - startTime - pausedSeconds //subtract time paused
let minutes = Int(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = Int(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
workoutTime.text = "(strMinutes) : (strSeconds)"
}
@IBAction func startButtonTapped(sender: AnyObject) {
if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
isTiming = true
isPaused = false
pausedIntervals = [] //reset the pausedTimeCollector on new workout
}
@IBAction func pauseAndContinueButtonTapped(sender: AnyObject) {
if isTiming == true && isPaused == false {
timer.invalidate() //Stop the Timer
isPaused = true //isPaused
isTiming = false //Stopped Timing
pausedTime = NSDate() //asuuming you are starting a brand new workout timer
pauseButton.setTitle("RESUME", forState: UIControlState.Normal) //Set Button to Continue state
} else if isTiming == false && isPaused == true {
let pausedSeconds = NSDate().timeIntervalSinceDate(pausedTime!) //get time paused
pausedIntervals.append(pausedSeconds) // add to paused time collector
pausedTime = nil //clear current paused state
if !timer.valid {
timer.invalidate()
//timer = nil
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(TimedWorkoutViewController.updatedTimer), userInfo: nil, repeats: true)
}
isPaused = false
isTiming = true
pauseButton.setTitle("PAUSE", forState: UIControlState.Normal) //Set Button to Continue state
}
}
}
这篇关于在 iOS 中暂停和恢复计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!