Search code examples
iosmacoscolorsstoryboard

Named colors via storyboard


For my MacOS app, I created a colors Asset catalog. The Deployment target for my project is 10.11.

When I set colors at the storyboard, I can choose from the colors asset. But when I try to set one of the named colors programmatically, I need to wrap it in

if #available(OSX 10.13, *) {
   view.backgroundColor = NSColor(named: "someColor")
} else {
   // Fallback on earlier versions
}

ORIGINAL QUESTION:

So the question is why I'm not getting any warnings for choosing those colors via the storyboard?

I guess I need to replace them with a custom color, or my app will crash on OS < 10.13, but I would expect the storyboard not to let me choose those colors because of the deployment target..

EDITED:

So the question is what happens when I'm using those colors via Storyboard? Would it crash the app? or maybe the storyboard can handle named colors even for OS versions < 10.13 ? Because I tried to use the named colors via the Storyboard, and I installed the app on a Mac with OS 10.12, and the app worked just fine. So I'm wondering what's the reason for that..

P.S This question is also relevant to iOS, where the min version for named colors is iOS 11


Solution

  • It will not crash your app. With Colors from Assets Catalog you have two options:

    1. Only use it with storyboards.
    2. Using UIColor(named: <#String #>) like you're trying to do in your question.

    The only problem is that UIColor(named:) is available in iOS 11.0+ (See documentation)

    So if you'd like to use it every time you need to think about fallback to the oldest version and that may be not quite right what you want.

    But there is an other solution build in into Xcode in Media library:

    enter image description here

    You can drag&drop colors from assets catalog and Xcode will create for you reference for this color that will work in iOS 10.0 as well.

    The actual line of code hidden in this color is:

    colorLiteral(red: 0.9411764706, green: 0.07843137255, blue: 0.07843137255, alpha: 1)

    So you can write a script that will generate this color for you.

    Some time ago I need similar solution so I did wrote a script that scan my whole project for assets catalogs and inside them find a colors sets and create UIColor extension containing all the colors from assets:

    You can find it here: https://github.com/JakubMazur/SwiftColorsGenerator and it's available to use through Marathon (https://github.com/JohnSundell/Marathon)