NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Lear more...
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)
    }
}
Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Check out our new book!

Swift Gems

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

Swift Gems

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

  • 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
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift