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