我使用委托人从我的模态中获取一个字符串值,当模态关闭时,我试图使用该字符串更新Label文本。当模式关闭时,我试图使用该字符串更新Label文本。然而,我得到了错误。Unexpectedly found nil while implicitly unwrapping an Optional value: file.. 我不知道如何解决这个问题。我想这是因为视图还没有激活。
import Cocoa
class ViewControllerA: NSViewController, SomeDelegate {
@IBOutlet weak var msgLabel: NSTextField!
var s: String = "";
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func setDetails(s: String) {
self.user = s;
print("Notified", self.s) // <-- prints: Notified hello again
msgLabel.stringValue = self.s <-- DOESN'T WORK
}
func showModal() -> Void {
msgLabel.stringValue = "hello" // <--- WORKS
let cbvc: NSViewController = {
return self.storyboard!.instantiateController(withIdentifier: "ControllerBVC")
as! NSViewController
}()
self.presentAsModalWindow(cbvc);
}
@IBAction func onBtn(_ sender: Any) {
self.showModal();
}
}
protocol SomeDelegate {
func setDetails(s: String)
}
class ViewControllerB: NSViewController {
@IBOutlet weak var textF: NSTextField!
var delegate: SomeDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
let vc = ViewControllerA()
self.delegate = vc
}
@IBAction func onBtn(_ sender: Any) {
DispatchQueue.main.async {
self.delegate?.setDetails(s: self.textF.stringValue)
self.dismiss("ControllerAVC")
}
}
}
你有很多问题。
在 ViewControllerB.viewDidLoad
的新实例。ViewControllerA
至 delegate
财产。不要这样做。你的viewDidLoad方法应该是这样的。
override func viewDidLoad() {
super.viewDidLoad()
}
在 showModal
办法 ViewControllerA
应将自己指定为 ViewControllerB
之前 ViewControllerB
它的呈现。
func showModal() -> Void {
let cbvc: NSViewController = {
let vc = self.storyboard!.instantiateController(withIdentifier: "ControllerBVC")
as! ViewControllerB
vc.delegate = self
return vc
}()
self.presentAsModalWindow(cbvc);
}
在 setDetails
方法只是将字符串直接分配到你的文本字段。
func setDetails(s: String) {
msgLabel.stringValue = s
}