Customize the style of links embedded in Text

KD Knowledge Diet
2 min readDec 24, 2024

--

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)
}
}

In this code, we create an AttributedString and customize the link by setting its properties, such as the link URL, underline style, and foreground color.

Conclusion:

Customizing the style of links embedded within SwiftUI Text views allows you to provide a visually appealing and consistent user experience. Whether you want to change the link color for the entire Text view, apply specific styles to individual links, or use AttributedString for fine-grained control, SwiftUI provides flexibility and options to meet your app’s design requirements.

--

--

KD Knowledge Diet
KD Knowledge Diet

Written by KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!

No responses yet