Changing the Background Color of a View

When working with storyboards in a macOS project, you may want to change the background color of a scene (view). The simplest way to do that is to use this command:

self.view.layer?.backgroundColor = NSColor.blue.cgColor

This simply assigns the color blue (or whatever value you want to insert there such as red or yellow) to the background of the view layer. Of course, writing specific color values into code isn’t very efficient because if you want to change the color, you have to rewrite the code for a new color.

A far better solution is to change the color using code and the simplest way to do that is to assign the backgroundColor of a view to a variable that represents a different color. One way to do this is to use the Color Panel (see this blog post covering the Color Panel).

So if you create a simple macOS project that uses storyboards, place a push button on the view controller and create an IBAction method with a name such as changeBKColor. Declare a color panel underneath the class ViewController line like this:

let colorPanel = NSColorWell()

Now inside your IBAction method, add code like this:

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

You’ll need to create a changeColor function like this:

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

If you run this program, a window will appear with a push button. Clicking the push button will run the IBAction method changeBKColor, which displays a color panel. Choosing a color from this color panel then changes the background of the view. The complete code in the ViewController.swift file should look like this:

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

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

}
January 23rd, 2017 by
HTML Snippets Powered By : XYZScripts.com