Juli IchSelber Juli IchSelber - 2 months ago 18
Swift Question

Compare Integers

I have two buttons in my project, which add score += 1 to two separate labels. My intention is to compare the Integers in the labels if they are equal or not and give out a result (in this case an Integer) in another separate label, which shows me the scenario. But by pressing one of the two buttons nothing happens. The label shows that the Integers are equal but that is not possible because the Integers in the labels are not equal anymore.

override func viewDidLoad() {
super.viewDidLoad()

if scoreAdd == scoreAdd1 {
time.text = "\(regulargame)"
}else {
overtime = regulargame + 30
time.text = "\(overtime)"
}

// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func btn1(_ sender: AnyObject) {
scoreAdd += 1
score1.text = "\(scoreAdd)"
}

@IBAction func btn2(_ sender: AnyObject) {
scoreAdd1 += 1
score2.text = "\(scoreAdd1)"
}


}

Answer

viewDidLoad will only be called when the View of the ViewController is loaded. If you want to check the integers every time a button is pressed, you must do it explicitly:

override func viewDidLoad() {
  super.viewDidLoad()
  self.setTimeText()
  // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func btn1(_ sender: AnyObject) {
    scoreAdd += 1
    score1.text = "\(scoreAdd)"

    self.setTimeText()
}

@IBAction func btn2(_ sender: AnyObject) {
    scoreAdd1 += 1
    score2.text = "\(scoreAdd1)"

    self.setTimeText()
}

/// Is called whenever a score changes
func setTimeText() {
    if scoreAdd == scoreAdd1 {
        time.text = "\(regulargame)"
    } else {
        overtime = regulargame + 30
        time.text = "\(overtime)"
    }
}