How to customize links in swiftUI?

By | September 17, 2024

Normally when user tap on url shown inside a SwiftUI Text or Link view, it opens in Safari by default. However we can customize that behavior by replacing the openURL environment key. We can either handle the link entirely or perhaps pass it back to the system to open once your custom action completes.

In below given example, we adjusts both a Link and a Text view so that all URLs are sent to a handleURLTap() method to be acted on:

    var body: some View {
        VStack {
            Link("Visit Apple", destination: URL(string: "https://apple.com")!)
            Text("[Visit Apple](https://apple.com)")
        }
        .environment(\.openURL, OpenURLAction(handler: handleURLTap))
    }
    
    func handleURLTap(_ url: URL) -> OpenURLAction.Result {
        print("Handle \(url) somehow")
        return .handled
    }

In above example you can see, handleURLTap() returns a OpenURLAction.Result value of .handled, which means the method accepted the link and acted on it. There are alternatives:

  • Use .discarded if you mean you weren’t able to handle the link.
  • Use .systemAction if you want to trigger the default behavior, perhaps in addition to your own logic.
  • Use .systemAction(someOtherURL) if you want to open a different URL using the default behavior, perhaps a modified version of the URL that was originally triggered.

One thing to note is, links will use your app’s accent color by default, but you can change that using the tint() modifier as shown below.

Text("[Visit Apple](https://apple.com)")
    .tint(.blue)

Leave a Reply

Your email address will not be published. Required fields are marked *