'SwiftUI macOS - Create clickable hyperlink

I would like to display a url that the user can click on in my macos app. What I have so far is this:

Text(url)
.onTapGesture {
    if let url = URL(string: self.url) {
        NSWorkspace.shared.open(url)
    }
}

However, this provides no visual indication to the user that the url is clickable. I want the text to be underlined and I want the cursor to change to a hand when the user hovers over it. How do I do that?

EDIT:

I found a custom extension for conditionally applying a modifier to a view from the swift forums:


extension View {

    func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> some View {
        if conditional {
            return AnyView(content(self))
        } else {
            return AnyView(self)
        }
    }

}

after combining it with @Asperi's answer, I now have this:


@State private var isHoveringOverURL = false

Button(action: {
    if let url = URL(string: self.url) {
        NSWorkspace.shared.open(url)
    }

}) {
    Text(self.url)
        .font(.caption)
        .foregroundColor(Color.blue)
        .if(isHoveringOverURL) {
            $0.underline()
        }

}
.buttonStyle(PlainButtonStyle())
.onHover { inside in
    if inside {
        self.isHoveringOverURL = true
        NSCursor.pointingHand.push()
    } else {
        self.isHoveringOverURL = false
        NSCursor.pop()
    }
}

preview



Solution 1:[1]

Do not use "Text" for this.

You need to use button:

Button("someLink") {
    FS.openTerminal(at: Urls.SshDir)
}
.buttonStyle(LinkButtonStyle())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew____Pls_Support_Ukraine