Access Objects In View Controller From Window Controller

I'm just getting into development on mac os and I made a simple app for the touch bar that allows you to change the color (with a nscolorpicker) of a label that is also on the touch bar.

Now I would like to get the same effect on the actual window like so: I change the color using the picker on the touch bar and the color of the colorwell in the window changes as well.

This is the code that I currently have for the touch bar actions:

import Cocoa
@available(OSX 10.12.2, *)
class MainWindowController: NSWindowController {


    @IBOutlet weak var cptHello: NSColorPickerTouchBarItem!
    @IBOutlet var lblHello: NSTextField!
    override func windowDidLoad() {
        super.windowDidLoad()

        /
  
        cptHello.color = NSColor.white
  
        setCol()
    }
    func setCol(){
  
        lblHello.textColor = cptHello.color
  
  
  
  
    }
    @IBAction func colorPicked(_ sender: Any) {

        setCol()
  
    }
}

This piece of code resides in MainWindowController.swift which is paired with the window controller.


In the view controller, I have a single NSColorWell that I would like to change the color for inside the function "setCol()". I created an outlet in the view controller for it like so:

@IBOutlet var cwHello: NSColorWell!


So ideally what I want to achieve is something like this:

  func setCol(){
      
        lblHello.textColor = cptHello.color
        ViewController.cwHello.color = cptHello.colr
      
      
      
    }


Can this be done at all?

You can send a notification from the NSWindowController and have your view controller addObserver to this notification.


This is a general pattern for communicating between 2 controllers.


You can also create a global var for tyhe viewController ; and use it to access to the cwHello from the windowController. But I find the first solution more clean.

If the view controller is the one associated with the content (root) view of your window, you can get a reference to it from a standard NSWindowController property:


     let viewController = contentViewController as! ViewController // It *must* be this type, so crash if it isn't
     viewController.cwHello.color = cptHello.colr

This is what is working for me :

 var viewController: ViewController {
        get {
            return self.window!.contentViewController! as! ViewController
        }
    }
...
viewController.cwHello.color = cptHello.colr
Access Objects In View Controller From Window Controller
 
 
Q