Ios Swift:在共享容器视图中更新标签

Ios Swift:在共享容器视图中更新标签,ios,swift,containers,Ios,Swift,Containers,背景: 我有三个ViewController,它们共享一个容器视图。ContainerViewController保存一个将被修改的变量,例如银行 我有一个按钮,可以给银行增加10000英镑。单击时,它会向银行增加10000英镑,但只有当您导航到另一个选项卡或返回时,它才会显示 我一直在研究这个问题,似乎明白我需要使用prepare(对于segue:)来更新它,但我似乎无法让它工作 问题:如何立即更新容器视图(因为我最终希望在其中添加其他标签),以便在同一个VC上反映和显示新值 HomeV

背景:

我有三个ViewController,它们共享一个容器视图。ContainerViewController保存一个将被修改的变量,例如银行

我有一个按钮,可以给银行增加10000英镑。单击时,它会向银行增加10000英镑,但只有当您导航到另一个选项卡或返回时,它才会显示


我一直在研究这个问题,似乎明白我需要使用prepare(对于segue:)来更新它,但我似乎无法让它工作

问题:如何立即更新容器视图(因为我最终希望在其中添加其他标签),以便在同一个VC上反映和显示新值

HomeViewController(带按钮)

视图控制器(容器)


有很多答案,例如,RxSwift可以帮助您,或者更简单的东西,比如通知中心。两者都与观察员合作,我希望这段代码可以帮助您

在容器视图中添加此代码

var bank = 10000
viewDidLoad(){
   NotificationCenter.default.addObserver(self, selector: #selector(updateLabel(_:)), name: NSNotification.Name(rawValue: "updateLabel"), object: nil)
}

@objc func updateLabel(_ notification: Notification){
    if let data = notification.object as? Int{
    bank += data
    cashLabel.text = "\(bank)"
    }
}
现在,在主视图控制器中添加此代码

@IBAction func bankButton(_ sender: Any) {
    bank += 10099
    print("\(bank)")
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateLabel"), object: bank)
}

我建议您研究一下RxSwift,并结合使用,后者只适用于iOS 13

谢谢!我收到一个错误,NSNotification.Name没有成员“didReceiveData”。我一定会在RxSwift上读到。
var bank = 10000
viewDidLoad(){
   NotificationCenter.default.addObserver(self, selector: #selector(updateLabel(_:)), name: NSNotification.Name(rawValue: "updateLabel"), object: nil)
}

@objc func updateLabel(_ notification: Notification){
    if let data = notification.object as? Int{
    bank += data
    cashLabel.text = "\(bank)"
    }
}
@IBAction func bankButton(_ sender: Any) {
    bank += 10099
    print("\(bank)")
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateLabel"), object: bank)
}