How can i change the same value between different view controllers?

夙愿已清 提交于 2021-01-28 22:14:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!