Yuri Malheiros Yuri Malheiros - 6 months ago 161
Swift Question

How to pass data from NSWindowController to its NSViewController?

I have a

IBOutlet
of a
NSToolBar
button in my
NSWindowController
class, which is my main window class:

class MainWindowController: NSWindowController {

@IBOutlet weak var myButton: NSButton!

// ...
}


I have a class
MainViewController
that is that content
NSViewController
of the main window.

How can I access this button in my content
NSViewController
? Is there a better way to organize the
IBOutlets
and the controllers to facilitate this access?

Answer

How about like this using delegate? This example will change your button's title.

@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
    }

}