gpt4 book ai didi

swift - 将秒转换为分钟 :Seconds in label MacOS

转载 作者:行者123 更新时间:2023-11-30 11:21:35 26 4
gpt4 key购买 nike

我是一名学校老师,我们被“命令”在类(class)中使用特定的计时器,但你瞧,这个计时器在我们的苹果 iMac 上不起作用。我正在尝试在 xcode 中创建自己的窗口,到目前为止已经创建了一个基本窗口,它将在几秒钟内对标签进行倒计时。我现在已经分配了按钮并且它们可以工作(以 60 秒为增量)。

enter image description here

这有效并且很好,但理想情况下我希望标签显示分钟和秒(对 child 来说更容易)。对此进行编码的最佳方法是什么?我上次使用 xcode 是在 2009 年,现在我已经过时了!提前致谢

--

    @objc func updateTimer() {

seconds -= 1 //This will decrement(count down)the seconds.
countdownLabel.stringValue = "\(seconds)" //This will update the label.
}

--

    @objc func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:(#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
}

--

    @IBAction func threeMin(_ sender: Any) {
seconds = 180
runTimer()
}

--

最佳答案

有很多解决方案。一个方便的方法是 DateComponentsFormatter

let formatter : DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .second]
return formatter
}()

@objc func updateTimer() {
seconds -= 1
countdownLabel.stringValue = formatter.string(from: TimeInterval(seconds))!
}
<小时/>

一些改进:

为所有按钮分配标签,其值以秒为单位,例如将 thirdMin 按钮的标签设置为 180。然后仅使用 one IBAction 并将所有按钮连接到该操作。

在操作中首先检查计时器是否正在运行,只有在没有运行时才启动它

var timer : Timer?

@IBAction func startTimer(_ sender: NSButton) {
if timer == nil {
seconds = sender.tag
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateTimer), userInfo: nil, repeats: true)

}
}

创建一个函数来可靠地停止计时器

func stopTimer() {
if timer != nil {
timer?.invalidate()
timer = nil
}
}

updateTimer()函数中,如果为0,则停止计时器

@objc func updateTimer() {
seconds -= 1
countdownLabel.stringValue = formatter.string(from: TimeInterval(seconds))!
if seconds == 0 { stopTimer() }
}

关于swift - 将秒转换为分钟 :Seconds in label MacOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51217883/

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