【发布时间】:2022-01-26 06:16:20
【问题描述】:
所以我的应用有 3 个屏幕:Main、Second 和 Result(非常简单)
-
在主屏幕上,我显示一个标签和按钮来更改它
-
在第二个中,我使用 textinput 更改标签并将其传递给 Result (有
导航控制器)
-
在最后一个屏幕上,我显示了结果和 2 个按钮:保存和 取消
我的问题是我无法为 Main 的 outlet 赋值,因为它是 nil,我不能对 viewDidLoad() 做任何事情,因为它只在应用启动时工作一次。
我能做些什么来解决这个问题?是否有任何功能可以重新加载视图,以便我可以在 viewDidLoad 中分配值?
整个应用在这里:https://drive.google.com/file/d/1mvL2fVxjOHbL4dReCwJ8poIq9G9-ezny/view
主VC:
class MainVC: UIViewController, ResultVCDelegate {
func passData(text: String) {
// label.text = text -- throws error
}
@IBOutlet weak var label: UILabel!
@IBAction func change(_ sender: Any) {
let nextVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NavVC")
present(nextVC, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
第二个VC:
class SecondVC: UIViewController {
@IBOutlet weak var inputText: UITextField!
@IBAction func save(_ sender: Any) {
let nextVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ResultVC") as! ResultVC
nextVC.labelText = inputText.text!
navigationController?.pushViewController(nextVC, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
结果VC:
protocol ResultVCDelegate {
func passData(text: String)
}
class ResultVC: UIViewController {
var delegate: ResultVCDelegate?
var labelText = ""
@IBOutlet weak var label: UILabel!
@IBAction func saveAndGoHome(_ sender: Any) {
let mainVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainVC") as! MainVC
self.delegate = mainVC
delegate?.passData(text: labelText)
dismiss(animated: true, completion: nil)
}
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
label.text = labelText.isEmpty ? label.text : labelText
}
}
顺便说一句:我用两个屏幕做了类似的应用程序,它就像一个魅力......奇怪
【问题讨论】:
-
在您的 ResultVC 中,您创建了 MainVC 的一个新实例。这不是您的原始实例,如果需要,您需要传递对 ResultVC 的引用
-
在实例化视图控制器后立即访问插座无法正常工作,因为视图尚未加载(尚未),这意味着插座未连接。
-
@Andrew 它可以工作,如果我将 print 放入 MainVC passData func 它会打印值
-
@vadian 听起来很奇怪,因为在 viewDidLoad() 中执行操作时它不起作用...
标签: ios swift delegates storyboard iboutlet