Better Programming

Advice for programmers.

Follow publication

How to Use and Define Custom Colors in SwiftUI

Create and use custom color variables in SwiftUI

Vinny Allen
Better Programming
Published in
3 min readMay 11, 2020

--

Create a New Project (or Use an Existing One)

Open Xcode and choose “Create a new Xcode Project.” Choose “Single View App.”

Click “Next” and give your product a name. Be sure that your language is set to “Swift” and your user interface is set to “SwiftUI.”

Click “Next.” Choose your project file location and click “Create.” Click “Resume” in the preview window to build your project. You should now see a view identical to the screen below:

Navigate to your Assets.xcassets folder. This is where all of your project resources — such as images, app icon files, and colors — live.

Right-click anywhere in the empty space under “Appicon,” choose “New folder,” and name it “Colors” (this step isn’t necessary, but it helps to keep things tidy).

Right-click the folder you just created and choose “New Color Set.” A color set is an instance variable that declares a color value. In the set, you can define variations of that color for Dark Mode, Light, or any as well as variations for different device types. I’ll go over this in another article.

Let’s start by importing our primary color set. Select the color swatch. In the Color Set Attributes panel to the right, you will see your options.

Name your first color and choose “8-bit Hexadecimal” for the input method. This is merely my preference, but I think it makes it much easier to copy and paste from Sketch.

Paste your hex code into the Hex field:

You should now see your color previewed in the swatch.

Repeat this step as needed to include all of your brand colors:

Using Your New Color Sets

There are two ways to use your custom colors in Swift UI.

  • Select your object in device preview. Choose “Color” under the attributes inspector. Your custom colors now show at the bottom of the list!

The great thing about SwiftUI is that the changes you make in device preview will be reflected in your code.

  • You can call your new color sets by calling:
Color("YourColorName")

To change the text color, add this property to your text object:

.foregroundColor(Color("YourColorName"))

Thanks for reading! Look out for more SwiftUI Basics articles coming soon.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Vinny Allen
Vinny Allen

Written by Vinny Allen

Product designer that sometimes writes code.

Responses (1)

Write a response