Skip to content
DeveloperMemos

Adding Color Gradients to Text in SwiftUI

iOS, SwiftUI, UI Design, Gradient Text1 min read

Adding color gradients to text in SwiftUI enhances the visual aesthetics of your application. Depending on the iOS version you are targeting, the approach varies. Here's a short guide on applying color gradients to text, covering both methods for pre-iOS 15 and post-iOS 15 versions.

Pre-iOS 15 Gradient Application

Step 1: Establishing the Text View

Start by creating a simple text view:

1Text("Gradient Text")

Step 2: Applying Gradient with Overlay and Mask

Next, apply the gradient using the .overlay() and .mask() modifiers. This method involves layering a gradient over the text and then masking it to the text's shape:

1Text("Gradient Text")
2 .font(.largeTitle)
3 .overlay(
4 LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .leading, endPoint: .trailing)
5 )
6 .mask(Text("Gradient Text").font(.largeTitle))

Post-iOS 15 Gradient Application with foregroundStyle

Step 1: Basic Text Setup

Similarly, start by defining your text view:

1Text("Gradient Text")

Step 2: Utilizing foregroundStyle for Gradient

In iOS 15 and later, applying gradients becomes more streamlined with the foregroundStyle modifier. This approach is more concise and directly applies the gradient as a foreground style to the text:

1Text("Gradient Text")
2 .font(.largeTitle)
3 .foregroundStyle(
4 LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .leading, endPoint: .trailing)
5 )

In conclusion, adding color gradients to text in SwiftUI offers a unique opportunity to enhance the visual appeal of your iOS applications. Whether you're working with pre-iOS 15 techniques involving .overlay and .mask, or utilizing the streamlined foregroundStyle in iOS 15 and later, both methods provide a pathway to create engaging and visually dynamic text elements - making them not only more attractive but also more engaging for your users!