Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make hyperlinks in SwiftUI

Tags:

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. this.

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(" .")         }     } } 
like image 308
Ika Avatar asked Sep 01 '19 08:09

Ika


People also ask

How do I add a link in SwiftUI?

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")!)

How do I add text in 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.


2 Answers

Swift 5.5 (iOS 15+)

1

Foundation supports Markdown.

Text("[Privacy Policy](https://example.com)") 

Explaination

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


2

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")!) 
like image 181
mahan Avatar answered Sep 27 '22 22:09

mahan


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 

Solution for using a String variable

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.

like image 43
Jacob Ahlberg Avatar answered Sep 27 '22 22:09

Jacob Ahlberg