视图加载时启动NSTimer

时间:2016-02-27 16:03:16

标签: swift nstimer viewdidload

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

@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)")
    }
}

我希望这种方式工作的方式是计时器在视图加载的那一刻开始。我不想按一个按钮让冒号开始闪烁。 提前致谢

1 个答案:

答案 0 :(得分:1)

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

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

我会做一点改进 - 因为OnOff变量本质上似乎是二元的 - 让我们做一个布尔类型:

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)")

}