Displaying a Color Panel in macOS Programs

The Cocoa framework contains standard panels your programs can use to Open, Save, or Print a file. Of course, you have to write code to make those panels work, but the Cocoa framework provides the code to display standard panels for your program to use.

One panel you can use is the Color Panel, which displays different colors for the user to choose from. To create a panel, you must first define a constant to represent that panel. For a color panel, the code needs to use the NSColorWell class like this:

let colorPanel = NSColorWell()

Next, you need to actually display that color panel using the activate command:

colorPanel.activate(true)

Once you’ve activated the color panel to display it, you need to retrieve the color value the user chooses. To do that, you need to use the action and #selector commands to run the changeColor function like this:

colorPanel.action = #selector(changeColor(_:))

You must write your own code in the changeColor function to make it actually do something. Assuming you have a label on your user interface called myLabel, you could change the label’s textColor property by retrieving the color panel’s color property like this:

    override func changeColor(_ sender: Any?) {
        myLabel.textColor = colorPanel.color
    }

So if you put a push button and a label on a window, clicking the push button would display the color panel. When the user chooses a color, the label’s text color would change. The complete code would look like this:

import Cocoa

class ViewController: NSViewController {

    @IBOutlet weak var myLabel: NSTextField!
    
    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.
        }
    }

    override func changeColor(_ sender: Any?) {
        myLabel.textColor = colorPanel.color
    }
    
    @IBAction func chooseColor(_ sender: NSButton) {
        colorPanel.activate(true)
        colorPanel.action = #selector(changeColor(_:))
    }

}

The main key to using the color panel is to call the changeColor function and add your own code to the changeColor function to make it do something.

As you can see, by using standard panels in your macOS programs, you can easily create a macOS program that looks and behaves like a regular macOS program without needing to write hardly any code.

December 12th, 2016 by
HTML Snippets Powered By : XYZScripts.com