Changing View Colors

I an using Xcode 11 with IB and I have working some code to change the background colors from a ViewController class. Is there a way to a smiliar thing from the window controller?


Here is the code I have in the ViewController..


import Cocoa

class ViewController: NSViewController {

    let colorPanel = NSColorWell()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func changeBKColor(_ sender: NSButton) {
        colorPanel.activate(true)
        colorPanel.action = #selector(changeColor)
    }

    @objc func changeColor(_ sender: Any?) {
    self.view.layer?.backgroundColor =  colorPanel.color.cgColor
    }

}

NSWindow has a "backgroundColor" variable that lets you set the window background color. NSWindowController has a variable "window" that contains the window the controller is controlling.

You should set the layer first in viewDidload


    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.wantsLayer = true
        self.view.layer?.backgroundColor = NSColor.blue.cgColor


Otherwise, I suspect you do noting here.

Check in your present code by adding this test (before you completed viewDidLoad)


    @objc func changeColor(_ sender: Any?) {
        print("Layer is", self.view.layer)
        self.view.layer?.backgroundColor =  colorPanel.color.cgColor
    }


You will probably see in log

Layer is nil

The present code did work without your suggested changes, but I added your suggestion to also set the initial color. Also, can you supply more detail how to have similar code working from a Wiindow Controller? I would like to have a toolbar item color wheel trigger a function to change the background color. I created a WindowController.swift file, would it go it there or in NSWindowController.h file?


Thanks for your help.

Changing View Colors
 
 
Q