ios - 从 ViewControllerA 更新 ViewControllerB 中的标签(ViewController 都位于同一 View 的容器中)

标签 ios swift

View Controller A 和 B 都在容器中,并一起形成一个 View 。
在 ViewControllerA 中我有一个按钮和一个标签,在 ViewControllerB 中我有一个标签。
两个标签都初始化为数字“5”。
通过按下 ViewControllerA 中的按钮,我想向每个标签添加 3,
即每个标签应显示“8”。
我认为这就像在 ViewControllerB 中定义一个函数来接受来自 ViewControllerA 的更新总计,然后更新 ViewControllerB 中标签的文本属性一样简单。
当然,我得到“在解包可选值时意外发现 nil”。
非常感谢建议/指导。

import UIKit

class ViewControllerA: UIViewController {

//MARK: Properties
@IBOutlet weak var buttonInViewControllerA: UIButton!
@IBOutlet weak var labelInViewControllerA: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: Actions

@IBAction func buttonActionInViewControllerA(_ sender: UIButton) {
    let a: String = String(Int(labelInViewControllerA.text!)! + 3)
    labelInViewControllerA.text = a
    ViewControllerB().add3(value: a)
}
}

class ViewControllerB: UIViewController {

//MARK: Properties
@IBOutlet weak var labelInViewControllerB: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func add3(value: String) {
    self.labelInViewControllerB.text = value
}
}

最佳答案

问题在于

@IBAction func buttonActionInViewControllerA(_ sender: UIButton) {
    // ...
    ViewControllerB().add3(value: a)

}

您创建了一个ViewControllerB的新实例。您需要的是对现有引用(属性)的引用(属性),然后您可以通知该引用(属性)有关更改的信息:

class ViewControllerA: UIViewController {
    var controllerB:ViewControllerB?

    // ...

    @IBAction func buttonActionInViewControllerA(_ sender: UIButton) {
        // ...
        controllerB?.add3(value: a)
    }
}

并且不要忘记在代码中的某个位置设置 controllerB,例如

var vcA = ViewControllerA()
var vcB = ViewControllerB()
vcA.controllerB = vcB
// dispaly vcA and vcB

关于ios - 从 ViewControllerA 更新 ViewControllerB 中的标签(ViewController 都位于同一 View 的容器中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54883584/

相关文章:

ios - 如何在swift中设置子类属性

swift - Xcode 14 Xcode 13 不兼容

ios - 在 Swift 中打开图表故事得到全白屏幕

ios - 使用 Eureka 表单的内存泄漏问题

ios - 调整 FontSizeToFitWidth 时裁剪 UILabel

javascript - 检测 iOS 中的水平触摸事件

ios - 如何获取 iOS 中可用系统声音的列表?

ios - 如何检查用户是否在 NSLocationAlwaysAndWhenInUseUsageDescription Swift 3.2 上单击否

ios - 在 MVVM 应用程序中访问核心数据堆栈

iOS 火力地堡 : Add data to firebase node of array type