In Swift, as shown here, you can use "NSMutableAttributedString" to embed links in text.
How can I achieve this with SwiftUI?
I implemented it as follows, but that does not look how I want it to. .
import SwiftUI struct ContentView: View { var body: some View { HStack { Text("By tapping Done, you agree to the ") Button(action: {}) { Text("privacy policy") } Text(" and ") Button(action: {}) { Text("terms of service") } Text(" .") } } }
SwiftUI gives us a dedicated Link view that looks like a button but opens a URL in Safari when pressed. It's easy enough to use – just give it a title for the button, plus a destination URL to show, like this: Link("Learn SwiftUI", destination: URL(string: "https://www.hackingwithswift.com/quick-start/swiftui")!)
Hold the command key and click the text to bring up a pop-over menu. Choose Show SwiftUI Inspector and then you can edit the text/font properties.
Foundation supports Markdown.
Text("[Privacy Policy](https://example.com)")
To create a link, enclose the link text in brackets (e.g., [Duck Duck Go]) and then follow it immediately with the URL in parentheses (e.g., (https://duckduckgo.com)).
My favorite search engine is [Duck Duck Go](https://duckduckgo.com).
https://www.markdownguide.org/basic-syntax/#links
Use Link
A control for navigating to a URL.
https://developer.apple.com/documentation/swiftui/link
Link("Privacy Policy", destination: URL(string: "https://example.com")!)
Just as @mahan mention, this works perfectly for iOS 15.0 and above by using markdown language:
Text("[Privacy Policy](https://example.com)")
But if you're using a String
variable, and put it into the Text
it wouldn't work. Example:
let privacyPolicyText = "Read our [Privacy Policy](https://example.com) here." Text(privacyPolicyText) // Will not work
The reason is that Text
got multiple initiations. So how do we solve this? The easiest way is just to do:
let privacyPolicyText = "Read our [Privacy Policy](https://example.com) here." Text(.init(privacyPolicyText))
Result: Read our Privacy Policy here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With