NSColor woes

In a current Swift App, I need to replace ALL my uses of NSColor with a method that allows me to use “Named Colors” specified as strings.

It seems the definition of an NSColor is one of 4 methods

  • specify the RGB value (such as NSColor(rgb:0xF3297A) )
  • specify one of the sematic colors (such as NSColor(named:“TextColor”)
  • specify one of the “standard colors” (such as NSColor.red)
  • specify one of the “system colors” (such as NSColor.systemblue)

The first two methods I can incorporate into a NSColor Extension quite easily.
I check if the “name” starts with &C (for example) and extract the hex value and use the RGB initializer. Otherwise I check the name on a list and use the “Named” initializer

HOWEVER. The last two won’t work that way, since they don’t exist in the “namelist” like those in the second bullet do. So NSColor(named:“red”) is not a valid syntax. Now for these I could use the RGB initializer since they do not change values between light and dark. but that still leaves the last bullet.

Those colors that are “systemXXXX” DO have different values between light and dark
So I can’t figure out a way to implement those

The idea was to add an extention to NSColor

so I could say

let myColor = NSColor(nameof : "systemBlue")

Any ideas?

Note : I know I can define my own versions in the Asset Catalog so I could use NAMED , but that is a duplication of what Apple already has done… but if there is no other way :frowning:

I found a way to use the RBG initlaizer and still have it honor light/dark

in the extenstion I added

convenience init(light: NSColor, dark: NSColor) {
          self.init(name: nil, dynamicProvider: { $0.name == .darkAqua ? dark : light })
      }

then defined the color by

case "SYSTEMBLUE"   : self.init(light:NSColor(rgb:0xFF0000),dark:NSColor(rgb:0x00FF00))

Note, those hex values are for test purposes only :slight_smile:

1 Like

I vaguely recall something about color catalogues and then you have to store the name and catalogue, then rebuild it that way… But it’s been a long while since I needed to save and restore colors.

Well for this app (which is macOS/Swift) it needs to know about and use/store iOS color names, some are shared with macOS, but some are unique to iOS.

So I have created an internal dictionary of all the color names (macOS AND iOS), and converted the standard colors (red, green etc) to this same means.

So now the app refers to ALL color references in the same manner

let color = NSColor(named:"red")

where this is an override of the normal “named” function that already exists, but refers to the dictionary instead of the Asset Catalog. Yes I could have defined them all in the catalog, but this method is cut/paste portable.