Reputation: 9409
My app involves two UILabels
labelDisplay
and labelStatus
, one UIButton
, buttonAddOne
, and a variable numbers
. I can't understand why the labelStatus
isn't being updated when numbers
reaches 5.
import UIKit
var numbers:Int = 0
class ViewController: UIViewController {
// Declaration of the two labels
@IBOutlet weak var labelDisplay: UILabel!
@IBOutlet weak var labelStatus: UILabel!
// Code for the "Add 1" button
@IBAction func buttonAddOne(sender: AnyObject) {
numbers = numbers + 1
labelDisplay.text = "\(numbers)"
}
override func viewDidLoad() {
super.viewDidLoad()
if numbers == 5 {
labelStatus.text = "Numbers variable is equal to 5! Hurray!"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Upvotes: 0
Views: 110
Reputation: 72750
The code you put in viewDidLoad
is executed once, when the view is loaded - it isn't triggered every time numbers
is updated.
To implement what you need, you should make number
an instance property, and add a didSet
observer:
class ViewController: UIViewController {
var numbers: Int = 0 {
didSet {
if numbers == 5 {
labelStatus.text = "Numbers variable is equal to 5! Hurray!"
}
}
}
...
}
The property observer is automatically executed when the property value is changed.
For more info read Property Observers
Upvotes: 1
Reputation: 534950
I can't understand why the labelStatus isn't being updated when "numbers" reaches 5
What would update it? The code inside viewDidLoad
? But viewDidLoad
is called once, early, when the view controller gets its view; it will never be called again, so that code will never run again.
If you want to update labelStatus
, why don't you do it in the same code that increments numbers
?
@IBAction func buttonAddOne(sender: AnyObject) {
numbers = numbers + 1
labelDisplay.text = "\(numbers)"
if numbers == 5 {
labelStatus.text = "Numbers variable is equal to 5! Hurray!"
}
}
Upvotes: 1