WWDC24 deal: 30% off our Swift and SwiftUI books! Learn more ...WWDC24 deal:30% off our Swift and SwiftUI books >>
Quick Tip Icon
Quick Tip

Customize the style of links embedded in Text

Since iOS 15 and macOS 12 we can embed links inside Text views in SwiftUI using Markdown or AttributedString.

There are a few different ways we can customize the visual appearance of such links.

To change the color of links in the entire Text view we can use tint() modifier.

Text("Visit our [website](https://example.com).")
    .tint(.purple)

We can also apply some customizations using Text modifiers and Text interpolation.

Text("Visit our \(Text("[website](https://example.com)").underline()).")

Note, that we can't change foreground color of the link by applying foregroundColor() modifier to the interpolated Text.

We can, however, construct our Text view with an AttributedString, which will allow us to apply various styles on per-link basis, including foreground color.

struct ContentView: View {
    var attributedString: AttributedString {
        var result = AttributedString("Visit our website.")
        
        // We can force unwrap the link range,
        // because we are sure in this case,
        // that `website` string is present.
        let linkRange = result.range(of: "website")!
        
        result[linkRange].link = URL(string: "https://example.com")
        result[linkRange].underlineStyle = Text.LineStyle(pattern: .dash)
        result[linkRange].foregroundColor = .purple
        
        return result
    }
    
    var body: some View {
        Text(attributedString)
    }
}
Books by Natalia PanferovaBooks by Natalia Panferova
WWDC24: 30% off all books!
  • Swift Gems

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

  • Integrating SwiftUI into UIKit Apps

    A detailed guide on gradually adopting SwiftUI in UIKit projects

The offer is active until the 16th of June.