NEW BOOK! SwiftUI Fundamentals: The essential guide to SwiftUI core concepts and APIs. Learn more ...NEW BOOK! SwiftUI Fundamentals:Master SwiftUI core concepts and APIs. Learn more...
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 underline() 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().

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

Deepen your understanding of SwiftUI!$35

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentalsby Natalia Panferova

  • Explore the key APIs and design patterns that form the foundation of SwiftUI
  • Develop a deep, practical understanding of how SwiftUI works under the hood
  • Learn from a former Apple engineer who worked on widely used SwiftUI APIs

Deepen your understanding of SwiftUI!

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

SwiftUI Fundamentals

by Natalia Panferova

$35