gpt4 book ai didi

swift - 在 MVVM 架构中实现 NSTimer

转载 作者:可可西里 更新时间:2023-10-31 23:35:35 28 4
gpt4 key购买 nike

我想实现一个 NSTimer 来使用 NSTimeInterval 显示一个计时器,所以我环顾四周,找到了这段代码,我将它放入了我的 ViewModel 层:

public class ViewModel {

public func startTimer() {
//if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
//}
}

@objc public func updateTime() -> String {
let currentTime = NSDate.timeIntervalSinceReferenceDate()

//Find the difference between current time and start time.

var elapsedTime: NSTimeInterval = currentTime - startTime

//calculate the minutes in elapsed time.

let minutes = UInt8(elapsedTime / 60.0)

elapsedTime -= (NSTimeInterval(minutes) * 60)

//calculate the seconds in elapsed time.

let seconds = UInt8(elapsedTime)

elapsedTime -= NSTimeInterval(seconds)

//add the leading zero for minutes, seconds and millseconds and store them as string constants

let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)

//concatenate minuets, seconds and milliseconds as assign it to the UILabel

return "\(strMinutes):\(strSeconds)"
}
}

我想在我的 View 中显示当前耗时,所以尝试了这个但没有成功:

viewModel?.startTimer()
timerLabel.text = viewModel?.updateTime()

如何在我的 ViewController 标签上显示 updateTime() 的最新结果?

最佳答案

updateTime 方法不能只返回字符串。它必须启动相关标签的更新。您可以对其进行编码以直接更新标签,也可以提供一个闭包,当它具有字符串值时 updateTime 将调用该闭包。

关于swift - 在 MVVM 架构中实现 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39059383/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com