swiftswiftui

How to make hyperlinks in SwiftUI


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 the following, but it 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(" .")
        }
    }
}

Solution

  • Motjaba Hosseni is right so far there is nothing that resembles NSAttributedString in SwiftUI. This should solve your problem for the time being:

    import SwiftUI
    
    struct ContentView: View {
        var body: some View {
            VStack {
                Text("By tapping Done, you agree to the ")
                HStack(spacing: 0) {
                    Button("privacy policy") {}
                    Text(" and ")
                    Button("terms of service") {}
                    Text(".")
                }
            }
        }
    }