查看加载时启动NSTimer
我想制作一个简单的时钟应用程序,其中冒号闪烁以使其看起来更好。我的代码到目前为止是:查看加载时启动NSTimer
@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)")
}
}
我想这样工作的方式是,计时器开始于视图加载的那一刻。我不想按一个按钮来让冒号开始闪烁。 在此先感谢
我没有看到任何问题与您的计时器(您的问题标题另有说明),据我可以告诉它应该在视图加载后每秒触发。
我注意到的一件事是您的代码执行路径中存在一个问题: 如果您更改变量(在第一个中),那么两个随后的if语句重叠,请继续阅读以查看我的解决方案。
稍加改进我会做 - 为OnOff
变量似乎是在自然二进制 - 让我们说一个boolean类型:
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)")
}
该解决方案更可读[http://importblogkit.com/2015/03/writing-readable-code/]。优秀。 – nhgrif
@nhgrif感谢您的输入,非常感谢。 –
非常感谢您的帮助。这工作出色。 –
你能详细说明什么是不准确的吗?目前看起来定时器会在视图加载时触发,之后每秒重复一次...您的代码对我来说看起来很好...... –
您似乎在打开显示器后立即关闭冒号。你希望打开和关闭多久? –
“时钟”部分丢失。你在哪里设置“小时”和“分钟”? – vadian