Color in SwiftUI can be used in various ways to enhance the appearance of your app. Color can be used in modifiers to change the background or foreground colors of views, or it can be used as a view itself.
Basic Code Sample
In this example, the text "Hello" will be red.
Text("Hello")
.foregroundColor(Color.red)There are various predefined colors you can use, such as Color.yellow, Color.green, and more.
Color in Modifiers
You can use Color in modifiers such as .foregroundColor and .background.
Text("Hello World!")
.foregroundColor(Color.red)
.background(Color.blue.opacity(0.5))Adding .opacity changes the color's transparency.
Color as a View
Color can also be used as a view. In this example, the resulting view is a blue square on top of a green background.
ZStack {
Color.green
.edgesIgnoringSafeArea(.all)
Color.blue
.frame(width: 100, height: 100)
}Modifiers such as .frame and .edgesIgnoringSafeArea can be used on Color, just like any other view.
System Colors
Color can take in system colors.
Color(.systemRed)System colors can adapt between light mode and dark mode. Apple's Human Interface Guidelines include a full list of system colors and their variants.
Custom Colors
Color can also take RGB values to display the color associated with those values. The example below displays cyan.
Color(red: 0.0, green: 1.0, blue: 1.0)If you choose to define colors this way in many places, it may be preferable to add reusable color sets to your project.
Color Sets
Color sets can be added in Assets.xcassets and then used throughout your views.
Color("Custom Color")In a color set, you can define light mode and dark mode versions using RGB values, hex codes, or system colors.
- Open
Assets.xcassetsin your project. - Add a new color set.
- Name the color set, such as
Custom Color. - Configure the light and dark appearances for that color.
- Reference the color by name in SwiftUI with
Color("Custom Color").
Tip: color sets are a good choice for app-wide brand colors because they keep visual values centralized and can adapt to light and dark mode.