Swift 在 NSToolbar 中使用 ColorPanel

Using the ColorPanel in the NSToolbar in Swift

我刚开始学习 swift,我正在尝试创建一个应用程序,它根据在 NSToolbar 的 NSColorPanel 中选择的颜色更改背景颜色。

单击 Colors 时,我会看到一个调色板。现在我想不通的是如何 extract/read Swift 中的颜色代码。

我在互联网上找遍了,但不幸的是没有任何帮助。

希望这里有人能提供更多信息。

首先你需要为颜色面板改变颜色时添加一个观察者。

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

其中 colorPanelDidChange 是您的自定义方法:

@objc func colorPanelDidChange(_ notification: NSNotification)

在此方法中,您提取通知的内容:

if let cp = notification.object as? NSColorPanel

现在您可以cp.color获取用户点击的实际颜色。