Search code examples
swiftxcodemacosnstoolbarnscolorpanel

Using the ColorPanel in the NSToolbar in Swift


I just started learning swift and I am trying to create an app that changes the color of the background based on the color selected in the NSColorPanel in the NSToolbar.

Toolbar Colors

When clicking on Colors I am faced a Color Palette. Now what I can't figure out is how to extract/read the Color Codes in Swift.

I have looked all over the internet but unfortunately nothing was helpful.

Hopefully someone here can provide with more information.


Solution

  • First you need to add an observer for when the color panel has changed colors.

    NotificationCenter.default.addObserver(self, selector: #selector(colorPanelDidChange(_:)),
                             name: NSColorPanel.colorDidChangeNotification, object: nil)
    

    where colorPanelDidChange is your custom method:

    @objc func colorPanelDidChange(_ notification: NSNotification)
    

    In this method, you extract the content of the notification:

    if let cp = notification.object as? NSColorPanel
    

    and now you can do cp.color to get the actual color the user has clicked on.