Hazar Panc
Hazar Panc

Reputation: 35

Update values on UI after a method makes changes on variables (Swift 3)

I'm new to swift. On my UI I have labels which display the values of some class instances. And, I have a class method that increases the value of those instances. After I call this method, my instance values do update; but the labels on the UI remain the same. How can I make this method also update my numbers in those labels.

Here is my ViewController code:

@IBOutlet weak var displayValue: UILabel! //this is the label that displays newNumber's value

override func viewDidLoad() {
    super.viewDidLoad()
    dispValue.text = String("\(newNumber.value))")
}

Here is my code:

class MyNumbers {
    var value = 50

    func increaseValue(by: Int){
       value += by
    }
}

var newNumber = myNumbers()
newNumber.increaseValue(by: 5) //This does increase newNumber's value to 55 
//but my label on my UI remains as 50 

Upvotes: 1

Views: 1593

Answers (1)

Aju Antony
Aju Antony

Reputation: 639

You need to assign the updated value to the UILabel. As best practice always make sure that you are invoking the UI Changes in main thread and also update the AutoLayouts when making a UI Update.

Replace:

newNumber.increaseValue(by: 5)

With:

DispatchQueue.main.async {
    newNumber.increaseValue(by: 5)
    self.displayValue.text = "\(newNumber.value)"
    self.view.layoutIfNeeded()
}

Upvotes: 1

Related Questions