视图控制器A和B都在容器中,并且一起形成一个视图。
在ViewControllerA中,我有一个按钮和一个标签,在ViewControllerB中,我有一个标签。
两个标签都初始化为数字“ 5”。
通过按ViewControllerA中的按钮,我想为每个标签添加3,
即每个标签应显示“ 8”。
我认为这就像在ViewControllerB中定义一个函数一样简单,可以从ViewControllerA接受更新的总计,然后在ViewControllerB中更新标签的text属性。
当然,我得到“在展开一个可选值时意外发现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/

10-12 00:16
查看更多