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

问题描述 投票:0回答:1

我使用委托人从我的模态中获取一个字符串值,当模态关闭时,我试图使用该字符串更新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")
                    }
    }
}
ios swift macos nstextfield
1个回答
2
投票

你有很多问题。

ViewControllerB.viewDidLoad 的新实例。ViewControllerAdelegate 财产。不要这样做。你的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
}
© www.soinside.com 2019 - 2024. All rights reserved.