Setting Custom Actions for Links in SwiftUI Text Views

KD Knowledge Diet
2 min readDec 19, 2024

--

Starting with iOS 15 and macOS 12, SwiftUI Text views offer the ability to include interactive links created with Markdown or AttributedString. This feature allows you to make specific portions of text within your Text views interactive, such as hyperlinks, and customize the actions associated with these links. In this guide, we’ll explore how to set custom actions for links in SwiftUI Text views using the `openURL` environment value.

Customizing Link Actions:

To customize the actions of links within SwiftUI Text views, you can use the `openURL` environment value. This value allows you to define a custom action handler for links. Here’s a step-by-step guide:

1. Create a Text View with Interactive Links:
Start by creating a Text view that contains interactive links using Markdown or AttributedString. In this example, we have a link to a website:

Text("Visit our [website](https://example.com)")

2. Define a Custom Action Handler:
To customize the action associated with the link, define a custom action handler. In this case, we create a function called `handleURL(_:)` that handles the URL when the link is tapped:

func handleURL(_ url: URL) {
// Customize the action for the URL here
}

3. Set the Custom Action Handler in the `openURL` Environment:
Use the `.environment(\.openURL, OpenURLAction { url in … })` modifier to set the custom action handler for links within the Text view. In the closure, you can call your `handleURL(_:)` function and customize the action. To indicate that the action has been handled, return `.handled`:

.environment(\.openURL, OpenURLAction { url in
handleURL(url)
return .handled
})

Now, when the user taps the link within the Text view, the `handleURL(_:)` function will be called, allowing you to implement custom actions such as opening a web page, navigating to another screen, or performing any other desired behavior.

Conclusion:

Customizing link actions in SwiftUI Text views using the `openURL` environment value provides greater control and flexibility in handling interactive links. By defining a custom action handler, you can tailor the behavior of links to suit your app’s requirements, enhancing the user experience and functionality of your SwiftUI-based applications.

--

--

KD Knowledge Diet
KD Knowledge Diet

Written by KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!

No responses yet