Link in SwiftUI

DevTechie Inc
Jun 24, 2022

Link view was introduced in iOS 14. Link view opens a url in Safari web browser when user clicks on it.

Let’s take a look at an example. We will create a local variable which will hold the link “https://www.devtechie.com” and create a URL object out of this urlString. This variable will be used with the Link view as shown below:

struct LinkExample: View {
    let destination = "https://www.devtechie.com"
    var body: some View {
        if let url = URL(string: destination) {
            Link("DevTechie", destination: url)
        }
    }
}
Link content doesn’t have to be a simple string but it can be any SwiftUI view. We will add two circles just like master card logo:

struct LinkExample: View {
    let destination = "https://www.devtechie.com"
    var body: some View {
        if let url = URL(string: destination) {
            Link(destination: url) {
                HStack {
                    Circle()
                        .fill(Color.red)
                        .offset(x: 40)
                    Circle()
                        .fill(Color.orange)
                        .offset(x: -40)
                        .opacity(0.8)
                }
            }
        }
    }
}
OpenUrl
OpenUrl is another keyPath added to Environment variable. If for some reason you don’t want to use Link view, you can achieve same functionality using openUrl keyPath as shown below:

struct OpenUrlExample: View {
    @Environment(\.openURL) var openURL
    
    let destination = "https://www.devtechie.com"
    var body: some View {
        if let url = URL(string: destination) {
            Button(action: {
                openURL(url)
            }) {
                Text("DevTechie")
            }
        }
    }
}


With that we have reached the end of this article. Thank you once again for reading. Subscribe to our weekly newsletter at https://www.devtechie.com