如何在不同的视图控制器之间更改相同的值? [英] How can i change the same value between different view controllers?

查看:24
本文介绍了如何在不同的视图控制器之间更改相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 swift/编程非常陌生,如果这是一个愚蠢的问题,请见谅,如果我的问题不够清楚,请见谅.

im very new to swift/programming, so sorry if this is dumb question or sorry if my question isnt clear enough.

名为Money"的黄色标签在每个视图控制器中必须具有相同的值,因此如果第一个视图控制器中的当前值为 1000,那么第二个视图控制器中的当前值为 1000.

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.

现在我按下那个写着加钱 200"的按钮,而不是 1000,黄色标签现在有 1200.再次按下加钱 200",我得到 1400.在第二个VC 中按加钱 400",然后现在我得到 1800.回到第一个 VC 并一遍又一遍地做.

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.

我该怎么做?我搜索了答案,唯一发现的是如何将价值从一个 VC 转移到另一个 VC,但我还没有找到任何地方如何来回转移价值.

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?

感谢关注:)

推荐答案

在你的 AppDelegate 中创建一个名为 money 的静态变量.

In your AppDelegate make static variable named money.

static var money = 1000

更新每个控制器的 viewWillAppear 中的黄色标签.

Update yellow label in viewWillAppear's of every controller.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    yellowLbl.text = AppDelegate.money
}

您可以在代码中的任何位置更新变量.如果你想加 200 美元,你可以简单地这样做.

You can update the variable anywhere in code. If you want to add 200 in money you can simply do this.

AppDelegate.money += 200

这篇关于如何在不同的视图控制器之间更改相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆