gpt4 book ai didi

swift - View 加载时启动 NSTimer

转载 作者:行者123 更新时间:2023-11-30 10:06:28 25 4
gpt4 key购买 nike

我想要制作一个简单的时钟应用程序,其中冒号会闪烁以使其看起来更好。到目前为止我的代码是:

@IBOutlet weak var clockLabel: UILabel!
var timerRunning = true
var timer = NSTimer()
var OnOff = 0
var colon = ":"
var hour = 0
var minute = 0

override func viewDidLoad() {
super.viewDidLoad()
clockLabel.text = ("\(hour)\(colon)\(minute)")
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "Counting", userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

func Counting(){
if OnOff == 1 {
OnOff = 0
colon = ":"
clockLabel.text = ("\(hour)\(colon)\(minute)")
}
if OnOff == 0 {
OnOff = 1
colon = ""
clockLabel.text = ("\(hour)\(colon)\(minute)")
}
}

我希望它的工作方式是计时器在 View 加载的那一刻开始。我不想按下按钮才能让冒号开始闪烁。提前致谢

最佳答案

我没有看到你的计时器有任何问题(你的问题标题表明不然),据我所知,它应该在 View 加载后每秒触发一次。

我注意到的一件事是代码执行路径中的一个问题:如果您更改变量(在第一个语句中),后续的两个 if 语句会重叠,因此请继续阅读以查看我的解决方案。

我会做一点改进 - 因为 OnOff 变量本质上似乎是二进制的 - 让我们将其设为 bool 类型:

var colonShown : Bool = false // this is your "OnOff" variable (changed it to be more clear to the reader + made it boolean (you treat it as a boolean, so why not make it boolean?))

然后,在您的计时函数中(我将其重命名为 tick()):

// renamed your Counting() function, no particular reason for that (sorry if that causes confusion) -- you can replace your Counting() function with this one (also make sure to update your timer selector that references the "Counting()" function on each "tick")
func tick(){
colonShown = !colonShown // toggle boolean value
colon = colonShown ? ":" : "" // neat one-liner for your if statement

clockLabel.text = ("\(hour)\(colon)\(minute)")

}

关于swift - View 加载时启动 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35671937/

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