Reputation: 21
I have want to make a simple clock app where the colon blinks to make it look better. My code so far is:
@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)")
}
}
The way I would like this to work is that the timer starts at exactly that moment when the view loads. I don't want to have to press a button to make the colon start blinking. Thanks in advance
Upvotes: 0
Views: 194
Reputation: 12820
I don't see any issue with your timer (Your question title suggests otherwise), as far as I can tell it should fire every second after the view loads.
One thing I did notice is an issue in your code execution path: The two consequent if statements overlap if you change the variable (in the first one), so read on to see my solution.
A little improvement I would make -- as the OnOff
variable seems to be binary in nature -- let's make that a boolean type:
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?))
And then, in your timing function (I renamed it to 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)")
}
Upvotes: 1