How to customize the way links are opened
About 2 min
How to customize the way links are opened 관련
SwiftUI by Example
Back to Home
How to customize the way links are opened | SwiftUI by Example
How to customize the way links are opened
Updated for Xcode 15
When your user taps a URL shown inside a SwiftUI Text
or Link
view, it will open in Safari by default. However, you can customize this behavior by replacing the openURL
environment key – you might want to handle the link entirely, or perhaps pass it back to the system to open once your custom action completes.
For example, this code adjusts both a Link
and a Text
view so that all URLs are sent to a handleURL()
method to be acted on:
struct ContentView: View {
var body: some View {
VStack {
Link("Visit Apple", destination: URL(string: "https://apple.com")!)
Text("[Visit Apple](https://apple.com)")
}
.environment(\.openURL, OpenURLAction(handler: handleURL))
}
func handleURL(_ url: URL) -> OpenURLAction.Result {
print("Handle \(url) somehow")
return .handled
}
}
As you can see, handleURL()
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.
Remember, links will use your app's accent color by default, but you can change that using the tint()
modifier:
Text("[Visit Apple](https://apple.com)")
.tint(.indigo)
Similar solutions…
How to open web links in Safari | SwiftUI by Example
How to open web links in Safari
Two-way bindings in SwiftUI | SwiftUI by Example
Two-way bindings in SwiftUI
How to adjust the way an image is fitted to its space | SwiftUI by Example
How to adjust the way an image is fitted to its space
How to let users customize toolbar buttons | SwiftUI by Example
How to let users customize toolbar buttons
How to customize the background color of navigation bars, tab bars, and toolbars | SwiftUI by Example
How to customize the background color of navigation bars, tab bars, and toolbars