Quick Tip Icon
Quick Tip

Interpolate text with custom foreground style in SwiftUI

SwiftUI lets us style portions of text by interpolating Text inside another Text and applying available text modifiers, such as foregroundColor() or font().

Starting from iOS 17 we can apply more intricate styling to ranges within a Text view with foregroundStyle().

For example, we can color a word with a gradient.

Screenshot of hello world text where world is colored with linear gradient Screenshot of hello world text where world is colored with linear gradient
struct ContentView: View {
    let gradient = LinearGradient(
        colors: [.blue, .green],
        startPoint: .leading,
        endPoint: .trailing
    )
    
    var body: some View {
        Text("Hello, \(Text("world").foregroundStyle(gradient))!")
            .bold()
            .font(.title)
            .textCase(.uppercase)
    }
}

And if you are interested in more advanced text styling, you can take a look at the new ShaderLibrary. In iOS 17 Metal shaders get automatically converted to ShapeStyles that then can be passed to foregroundStyle().


If you have older iOS apps and want to enhance them with modern SwiftUI features, check out my book Integrating SwiftUI into UIKit Apps. It provides detailed guidance on gradually adopting SwiftUI in your UIKit projects. Additionally, if you're eager to enhance your Swift programming skills, my latest book Swift Gems offers over a hundred advanced tips and techniques, including optimizing collections, handling strings, mastering asynchronous programming, and debugging, to take your Swift code to the next level.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35