Skip to main content

How to customize the way links are opened

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

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
    }
}

Download this as an Xcode project

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:

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)

Download this as an Xcode project

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