Register for Prevent bottlenecks during mobile development on September 13
Register
White arrow point right
App Development

Using Colors in SwiftUI: A Guide

Juan Reyes
Juan Reyes
Using Colors in SwiftUI: A Guide
January 10, 2023
9
min read

Creating elegant and feature-rich UIs can be a complex ordeal of rules and calculations. For many, it is a daunting endeavor. But it doesn't have to be. 

Today, we will be exploring one of the most critical aspects of design in SwiftUI: colors. In UI design, the use of colors is one of the most effective ways to convey information, create a visual hierarchy, and enhance the overall aesthetic of an app. And getting it right has never been easier.

This article will explain various ways of using colors in SwiftUI, including working with system colors, creating custom colors, and applying color styles to text and shapes. Additionally, we will create a simple example app that illustrates all the concepts explored in this article.

It may go without saying, but you probably won't be able to follow the article if you don't already have some foundation in Swift. To ensure that everyone is on the same page, following is a brief introduction to SwiftUI.

You can find more articles introducing you to Swift on the blog index here.

Alright, let's get into it.

SwiftUI Introduction

Apple's guidelines for UI design have evolved into SwiftUI, created expressly to interact with the Swift language infrastructure. Since code and an intuitive design language are pretty robust and straightforward to use in iOS, macOS, and all other Apple ecosystems, SwiftUI represents a new technique for creating app user interfaces. 

As stated in Apple's documentation. "SwiftUI provides views, controls, and layout structures for declaring your app's user interface. The framework provides event handlers for delivering taps, gestures, and other types of input to your app, and tools to manage the flow of data from your app's models down to the views and controls that users see and interact with." 

Typically, a SwiftUI project begins with two files: an App.swift file and a ContentView.swift file. 

SwiftUI views adhere to a fundamental framework and are defined in classes known as View Classes. A PreviewView struct helps the emulator display your work in real time, while a View struct specifies the view structure and capabilities.

Additionally, the body of the ContentView is defined by a variable of type View with the name "body." The current view will change visually if this variable changes.

A basic TextView element with the text "Hello World!" usually is present in all brand-new view classes.

Let's continue.

SwiftUI System Colors

SwiftUI provides a range of default system colors that you can use to match the appearance of native iOS, macOS, watchOS, and tvOS interfaces. These colors are defined in the Color struct.

The default system colors are designed to be automatically adjusted based on the user's preferred color scheme and accessibility settings. For example, if a user has enabled the "Reduce Transparency" accessibility preference, the system colors will automatically adjust to be more legible on a darker background.

You can refer to the Apple documentation for a complete list of available default system colors.

Some examples of system colors include:

  • Color.gray: A light gray color.
  • Color.red: A red color.
  • Color.green: A green color.
  • Color.yellow: A yellow color.
  • Color.blue: A blue color.
  • Color.pink: A pink color.
  • Color.purple: A purple color.
  • Color.teal: A teal color.

SwiftUI Custom Colors

In addition to using system colors, you can create custom colors in SwiftUI using the Color struct's init(red:green:blue:opacity:) initializer. This initializer takes four parameters: red, green, blue, and opacity. Each parameter is a value between 0 and 1, representing the intensity of the corresponding color channel.

For example, to create a custom orange color, you could use the following code:

let orange = Color(red: 1, green: 0.5, blue: 0, opacity: 1)

You can also use the Color struct's init(hue:saturation:brightness:opacity:) initializer to create a color using the HSB color model. This initializer takes four parameters: hue, saturation, brightness, and opacity.

The hue parameter is a value between 0 and 1 representing the color's position on the color wheel, with 0 being red, 0.17 being yellow, 0.33 being green, 0.5 being cyan, 0.67 being blue, 0.83 being magenta, and 1 being red again.

The saturation parameter is a value between 0 and 1 representing the color's intensity, with 0 being a grayscale color and 1 being a fully saturated color.

Finally, the brightness parameter is a value between 0 and 1, representing the color's luminosity, with 0 being black and 1 being white.

For example, to create a custom pink color, you could use the following code:


let pink = Color(hue: 0.9, saturation: 0.8, brightness: 0.9, opacity: 1)

SwiftUI Color Grayscale

In addition to applying colors directly to views, SwiftUI provides a way to modify the grayscale of the colors. For example, to apply a color grayscale to some text, you can use the .grayscale() modifier and pass in a value.


Text("Hello, world!").foregroundColor(.red).grayscale(Double($0) * 0.1999)

A color grayscale can help display content in a more accessible way for users with color blindness or other visual impairments.

Accessibility

It's important to consider accessibility when using colors in your app. For example, some users may have difficulty distinguishing between specific colors or not see colors at all. To ensure that your app is accessible to all users, you should consider the following best practices:

  • Use system colors and color styles whenever possible. These colors are designed to adjust automatically based on the user's preferred color scheme and accessibility settings.
  • Avoid using colors as the only means of conveying information. Use text labels or other visual elements in addition to colors to ensure your app's content is understandable to all users.
  • Use the .accessibility(label:) modifier to provide a text label for colors that convey essential information. This text label will be read aloud by VoiceOver, making it easier for users with visual impairments to understand your app's content.

Using Colors in a SwiftUI App

Here is an in-depth example of using colors in a SwiftUI app.


struct ContentView: View { var body: some View { VStack { // Use a system color as the background color of a view Rectangle() .fill(Color.blue) .frame(height: 200) .padding(40) // Use a custom color to create a button Button(action: { print("Button tapped") }) { Text("Custom button") .foregroundColor(.white) .padding() .background(Color(red: 0.5, green: 0.2, blue: 0.9, opacity: 1)) .cornerRadius(8) } // Use a color style to display grayscale text Text("Grayscale text") .foregroundColor(.gray) // Use the .accessibility(label:) modifier to provide a text label for a color Circle() .fill(Color.red) .padding(40) .accessibility(label: Text("Important information")) } } }

In this example, we use a system color as the background color of a view, create a custom color for a button, apply a color style to some text, and use the .accessibility(label:) modifier to provide a text label for a color.

The resulting app would display a blue rectangle at the top, a custom purple button with white text, some grayscale text, and a red circle with the text label "Important information" when using VoiceOver.

If you want to check out the full code, you can find it here.

Additionally, if you want to make sure that your code works well, it's important to develop a robust testing workflow. And if you want to dive deeper into the intricacies of UI testing and Unit Testing in Swift, you can read more about it in this article.

However, I advise you to look into Waldo.io's extensive toolkit for UI testing if you don't want to deal with the difficulties of creating a testing methodology. Even for non-developers, it is incredibly approachable and doesn't require any code.

You can start a free trial here.   

Conclusion

This article explored various ways of using colors in SwiftUI, including working with system colors, creating custom colors, and applying color grayscales to text and shapes. By understanding how to use colors in your app effectively, you can create visually appealing and accessible user interfaces that enhance the user experience.

Automate testing for your mobile app.Start building your first test for free

Subscribe to our newsletter for the latest news and resources

Thank you for subscribing to our blog!