@Fran Martin 接受的答案效果很好!
由于我在Swift中使用它,我花了大约一个小时来找出正确的Timer()
功能。为了帮助下一个不流利使用Objective C的人,这里是已接受答案的Swift版本,其中包含一些额外的计时器功能,invalidate
将计时器重置回00:00
,何时使用它viewWillAppear
,以及何时使用invalidate
它
始终 invalidate
使用计时器,viewWillDisappear
否则viewDidDisappear
如果它是repeat
计时器并且正在运行,您可以获得memory leak
我遇到了一个无法预料的问题,即使我会停止计时器,它也会继续运行,我发现这个SO Answer说你必须在再次启动它之前停止它以及当你声明计时器使用时weak
@IBOutlet weak fileprivate var yourLabel: UILabel!
var timeMin = 0
var timeSec = 0
weak var timer: Timer?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// if your presenting this vc yourLabel.txt will show 00:00
yourLabel.txt = String(format: "%02d:%02d", timeMin, timeSec)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
resetTimerToZero()
}
// MARK:- recordButton
@IBAction fileprivate func recordButtonTapped(_ sender: UIButton) {
startTimer()
movieFileOutput.startRecording(to: videoUrl, recordingDelegate: self)
}
// MARK:- Timer Functions
fileprivate func startTimer(){
// if you want the timer to reset to 0 every time the user presses record you can uncomment out either of these 2 lines
// timeSec = 0
// timeMin = 0
// If you don't use the 2 lines above then the timer will continue from whatever time it was stopped at
let timeNow = String(format: "%02d:%02d", timeMin, timeSec)
yourLabel.txt = timeNow
stopTimer() // stop it at it's current time before starting it again
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
self?.timerTick()
}
}
@objc fileprivate func timerTick(){
timeSec += 1
if timeSec == 60{
timeSec = 0
timeMin += 1
}
let timeNow = String(format: "%02d:%02d", timeMin, timeSec)
yourLabel.txt = timeNow
}
// resets both vars back to 0 and when the timer starts again it will start at 0
@objc fileprivate func resetTimerToZero(){
timeSec = 0
timeMin = 0
stopTimer()
}
// if you need to reset the timer to 0 and yourLabel.txt back to 00:00
@objc fileprivate resetTimerAndLabel(){
resetTimerToZero()
yourLabel.txt = String(format: "%02d:%02d", timeMin, timeSec)
}
// stops the timer at it's current time
@objc fileprivate stopTimer(){
timer?.invalidate()
}