【发布时间】:2019-02-26 10:39:57
【问题描述】:
视图控制器 A 和 B 都在容器中,并一起形成一个视图。
在 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
}
}
【问题讨论】:
-
这是因为,viewControllerB 还没有加载。当 viewControllerB 被加载时,您必须检查标签的更新值。对于修复,您可以添加一个保护语句以防止 add3 函数中的崩溃,例如 ..guard self.isViewLoaded else { return } 在访问该标签之前
-
但是 ViewControllerB 显示在屏幕上,并显示值为 5 的标签。这不意味着它已经加载了吗? (视图控制器 A 和 B 都在容器中并构成单个视图的一部分)。如果我将以下语句放入 viewDidLoad(在 ViewControllerB 中): print("Value of label in ViewControllerB is", labelInViewControllerB.text) 然后它会打印值“5”,这对我来说表示 ViewControllerB 已经加载并且 UILabel已初始化。
-
那么就获取viewControllerB的引用,(从viewControllerA,self.parent?.children.last as?viewControllerB)。我假设 viewControllerB 是最后一个孩子
-
PS:谢谢你的快速回复,顺便说一句。
-
如果我假设这将被添加到 ViewControllerA 中的 IBAction 中,那么整行会是什么样子?