如何连续重复此功能而不是使其失效?我已经在代码底部标出了else部分,它目前只是显示一个标题而不是重复整个功能。
func handleTimer(_ timer: Timer) {
if let currentPhase = self.phasesInProgress.last, let timerStart = timerStart {
debugPrint("Current Phase: \(currentPhase.title)")
let currentPhaseEndTime = TimeInterval(currentPhase.endTime)
let elapsedTime = abs(timerStart.timeIntervalSinceNow)
debugPrint("Elapsed Time: \(elapsedTime)")
if elapsedTime > currentPhaseEndTime {
debugPrint("Phase over current > \(currentPhaseEndTime), going to next.")
self.phasesInProgress.removeLast()
handleTimer(timer)
} else {
let phaseElapsed = elapsedTime - currentPhase.startTime
let duration = currentPhase.endTime - currentPhase.startTime
phaseTimeElapsedChanged(phaseElapsed, duration)
phaseChanged(currentPhase.title)
}
// } else {
// self.timer?.invalidate()
// self.completion()
}
这是计时器部分,但它没有重复该功能。
func start() {
phasesInProgress = phases.reversed()
timerStart = Date()
let aTimer = Timer(timeInterval: 1.0, repeats: true, block: { [weak
self] (blockTimer) in
self?.handleTimer(blockTimer)
})
timer = aTimer
RunLoop.current.add(aTimer, forMode: .defaultRunLoopMode)
aTimer.fire()
}
这是init
的部分init(settings: MeditationSettings, phaseChangedBlock: @escaping StringClosure, timeChangedBlock: @escaping DoubleDoubleClosure, completion: @escaping VoidClosure) {
self.phaseChanged = phaseChangedBlock
self.phaseTimeElapsedChanged = timeChangedBlock
self.completion = completion
addPhase(with: "Breathe In", duration: settings.breathIn)
addPhase(with: "Hold", duration: settings.breathInHold)
addPhase(with: "Breathe Out", duration: settings.breathOut)
addPhase(with: "Hold", duration: settings.breathOutHold)
}
答案 0 :(得分:0)
您正在尝试使用Timer
来重复某个功能,因此首先需要在您的班级上创建Timer
属性
var myTimer: Timer!
之后,必须实例化Timer并指示它在所需的时间间隔内执行所需的选择器
myTimer = Timer.scheduledTimer(timeInterval: 5,
target: self,
selector: #selector(functionToExecute),
userInfo: nil,
repeats: true)
因此通常会创建该函数
func functionToExecute() {
// perform your tasks here
}
最后,当您完成代码执行后,您只需要使Timer无效。例如,您可以使viewDidDisappear()
方法无效。
myTimer.invalidate()
答案 1 :(得分:0)
在主线程中启动计时器,如下所示:
func start() {
phasesInProgress = phases.reversed()
timerStart = Date()
var aTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { [weak self] (blockTimer) in
self?.handleTimer(blockTimer)
})
timer = aTimer
RunLoop.current.add(aTimer, forMode: .defaultRunLoopMode)
aTimer.fire()
}