如何将数据从NSWindowController传递到NSViewController?

Yur*_*ros 11 macos cocoa swift

我有一个IBOutlet一个的NSToolBar按钮在我的NSWindowController课,这是我的主要窗口类:

class MainWindowController: NSWindowController {

    @IBOutlet weak var myButton: NSButton!

    // ...
}
Run Code Online (Sandbox Code Playgroud)

我有一个类MainViewControllerNSViewController主窗口的内容.

如何在我的内容中访问此按钮NSViewController?有没有更好的方法来组织IBOutlets和控制器来促进这种访问?

Man*_*ius 9

要从NSWindowController访问NSViewController:

let viewController:MainViewController = self.window!.contentViewController as! MainViewController
Run Code Online (Sandbox Code Playgroud)

从NSViewController访问NSWindowController:

let windowController:MainWindowController = self.view.window?.windowController as! MainWindowController
Run Code Online (Sandbox Code Playgroud)


Pro*_*tto 8

这样使用委托怎么样?此示例将更改按钮的标题.

@objc protocol SomeDelegate {
    func changeTitle(title: String)
}

class ViewController: NSViewController {

    weak var delegate: SomeDelegate?

    @IBAction func myAction(sender: AnyObject) {
        delegate?.changeTitle("NewTitle")
    }

}

class MainWindowController: NSWindowController, SomeDelegate {

    @IBOutlet weak var myButton: NSButton!

    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.
        let myVc = window!.contentViewController as! ViewController
        myVc.delegate = self

    }

    func changeTitle(title: String) {
        myButton.title = title
    }

}
Run Code Online (Sandbox Code Playgroud)