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/