How to detect color panel's color change in Mac Catalyst app?

288 views Asked by At

In Mac Catalyst, there is a default toolbar item that shows a color panel.

https://developer.apple.com/documentation/appkit/nstoolbaritem/identifier/1531463-showcolors

It shows up just fine, but I can't find a way to detect a color change from this color panel. Does anyone know how to do this?

enter image description here

1

There are 1 answers

4
Hejazi On BEST ANSWER

When the toolbar item is clicked, an instance of NSColorPanel is shown. The selected color can be accessed from NSColorPanel.color, but we don't have a reference to the shown panel. Even the class NSColorPanel isn't visible to Mac Catalyst apps.

Fortunately, there is a notification that is posted when a color is selected in a color panel. So, all we need is to observe that notification to get a reference to the NSColorPanel instance, and then access its color property:

NotificationCenter.default.addObserver(forName: .init("NSColorPanelColorDidChangeNotification"), object: nil, queue: nil) { notification in
    let color = (notification.object as? NSObject)?.value(forKey: "color") as? UIColor
    print("Color changed", color)
}