模态关闭后更改主控制器上的标签文本 swift macOS

Changing Label text on main controller after modal closed swift macOS

我正在使用委托从我的模式中获取字符串值。当模式关闭时,我正在尝试使用该字符串更新标签文本。但是,我收到错误消息:在隐式展开可选值时意外发现 nil: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
}