Vlad Stoica Vlad Stoica - 1 year ago 50
Swift Question

Need button to change labels when clicked

i-m trying to learn how to code and working on my first ever app. it is some gym app. and i want to have a timer and a label to be changed after presing a button.
This is my code until now but i cant figure it out how to display the next label and the next timer to countdown after presing the button.

class _daysday1ViewController: UIViewController {

@IBOutlet weak var exerciseNameLabel: UILabel!
@IBOutlet weak var btnStart: UIButton!

@IBOutlet weak var exercisePicture: UIImageView!

@IBOutlet weak var exerciseDescriptionLabel: UILabel!

@IBOutlet weak var timerLabel: UILabel!

@IBAction func nextButtonTapped(sender: AnyObject) {

var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
count = countList[0]


var exerciseIndex = 0

var exerciseList = ["12 reps at 80% of capicity" , " 10 reps at 90%" , "7 to 10 reps at full capacity"]

var countList = [4 , 6 ,8]

var count = 1

override func viewDidLoad() {


func update() {
if(count >= 0) {
timerLabel.text = String(count--)
self.btnStart.enabled = false

btnStart.enabled = true
exerciseDescriptionLabel.text = exerciseList[0]



Answer Source

Your timer will go away almost as soon as it's created, because you declared the timer var within the nextButtonTapped function. That function finishes quickly, and your timer goes away when it finishes.

To fix this, declare the timer var at the class level, the same place you declared the count var, like this:

var timer: NSTimer?

Declaring it as an optional (?) allows it be nil until the next button is tapped.

To create it, simply change the line of code in nextButtonTapped to begin with this:

self.timer = ...

Instead of this:

var timer = ...