问题
im very new to swift/programming, so sorry if this is dumb question or sorry if my question isnt clear enough.
The yellow label named "Money" has got to be the same value in every viewcontroller, so if the current value is 1000 in the first viewcontroller, its also 1000 in the second viewcontroller.
Now i press that button that says "add money 200" and instead of 1000, the yellow label now has 1200. Press the "add money 200" again and i get 1400. Press "add money 400" in the secondVC and now i get 1800. Go back to the firstVC and do it again and again.
How can i do this? I searched for answers and the only thing that i found out is how to transfer a value from one VC to another, but i haven't found anywhere how to transfer the value back and forth back and forth.
So can anybody tell me how i can do this? Or at least point me in the right direction?
Thanks for the attention :)
回答1:
In your AppDelegate make static variable named money.
static var money = 1000
Update yellow label in viewWillAppear's of every controller.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
yellowLbl.text = AppDelegate.money
}
You can update the variable anywhere in code. If you want to add 200 in money you can simply do this.
AppDelegate.money += 200
来源:https://stackoverflow.com/questions/60584688/how-can-i-change-the-same-value-between-different-view-controllers