How to Define Custom URL Actions for SwiftUI Text Views
Find out interesting ways to use the custom URL actions.
--
This article is originally published at swiftsenpai.com
With the release of iOS 15, Apple has introduced native markdown support to the SwiftUI Text view. This feature allows developers to easily create strings with hyperlinks that can open websites, send emails, or make phone calls. While this feature may be sufficient in most cases, there are situations where developers might want more control over what happens when a link is tapped.
In this article, I will show you how to achieve greater control over link behavior in SwiftUI. Additionally, I will also share a few interesting use cases of custom URL action that you might find useful.
So, without further ado, let’s jump right in!
Using the `openURL` Environment View Modifier
With the release of iOS 15, Apple introduced the openURL
environment view modifier, along with markdown support in the Text
view. This modifier allows developers to define the action that will occur when a link is tapped. It can be easily used by appending it to a Text
view, as shown in the sample code below:
Text("Find out more [here](https://www.apple.com)")
.environment(\.openURL, OpenURLAction { url in
// Do something here...
return .systemAction
})
It is important to note that at the end of the action handler, it is required to return the result of the action performed. This ensures that the system knows the final outcome of the custom action.
If you’re wondering about the available action results, here is a list of all the possibilities:
In the next section, we’ll take a look at some of the interesting use cases for this modifier.
Some Interesting Use Cases
Now that you understand how the openURL
environment view modifier works, let’s take a look at a few of its interesting use…