Yohida Steroflisk Yohida Steroflisk - 1 month ago 8
Swift Question

Want to understand a relation

I am a beginner learning Swift 3 in Xcode 8 and I was building a basic app called "Eggtimer". The code is written below and I don't understand how the

timerlabel.text
is linked to timer even I didn't set any connection between them.

Next to the star
//*
we can also write
} else { timer.invalidate()
and the
labeltimer.text
nicely stops decreasing, how it can happen? What does the
selector
in
timer
properties mean?
Sorry for my English and thanks for your answers.

class ViewController: UIViewController {
var timer = Timer()
var time = 210

func decreasetimer() {
if time > 0 {
time -= 1
timerlabel.text = String(time)
} else { //*
timerlabel.text = String(time)
}
}

@IBOutlet var timerlabel: UILabel!

@IBAction func timerstarter(_ sender: AnyObject) {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.processtimer), userInfo: nil, repeats: true)
}
}

Answer

Lets start from the bottom: selector specifies the method which should be called every 1 second (timeInterval parameter). In your case this should be changed to the following:

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.decreasetimer), userInfo: nil, repeats: true)

As you can see the selector is called decreasetimer, which is the method you specified in the top.

The timer now calls this method every time it updates. In this method you decrease the time var and update the text of the timerlabel.

timer.invalidate() stopps the timer when time reaches 0.

I hope this clarifies your questions.

Comments