在将委托从NSWindowController子类传递到我的ViewController时遇到问题

时间:2018-12-28 20:53:12

标签: swift cocoa delegates protocols nswindowcontroller

我从MainWindowController(它是NSWindowController的子类)将自定义协议(MainWindowControllerProtocol)传递到EditorViewController时遇到问题。请帮忙。

EditorViewController.swift

extension EditorViewController: MainWindowControllerProtocol {
    func didOpenFile() {
        print("TODO: Open File") // never called, but it should be
    }
}

class EditorViewController: NSViewController {
    // - IBOutlets
    @IBOutlet weak var treeOutlineView: NSOutlineView!
    @IBOutlet var codeTextView: NSTextView!

    @IBOutlet weak var counterTextField: NSTextField!
    @IBOutlet weak var languageTextField: NSTextField!

    //public var editor = Editor()
    //var rootNode: Node?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.

        //rootNode = Path(Path.userDownloads).node

        // Issue is here
        if let windowController = NSApplication.shared.mainWindow?.windowController as? MainWindowController {
            windowController.delegate = self
        }
        else {
            print("Doesnt work") // prints this
        }

        //treeOutlineView.reloadData()
    }
}

MainWindowController

public protocol MainWindowControllerProtocol {
    func didOpenFile()
}

class MainWindowController: NSWindowController {

    var delegate: MainWindowControllerProtocol?

    override func windowDidLoad() {
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    }
    @IBAction func openFile(_ sender: Any) {
        print("In here") // this is called?
        delegate?.didOpenFile() // but this never is apparently
    }

}

1 个答案:

答案 0 :(得分:0)

也许this topic应该有所帮助。

  

如果应用程序的nib文件没有,此方法可能返回nil   完成加载,如果接收器未处于活动状态,或者应用程序   隐藏。

您是否检查了NSApplication.shared.mainWindow是否为nil或仅NSApplication.shared.mainWindow?.windowController是否不能转换为控制器类?