Chapter 40
How to Use ShareLink for Sharing Data Like Text and Photos

In iOS 16, SwiftUI released a new view called ShareLink. When users tap on the share link, it presents a share sheet for users to share content with other applications or copy the data for later use.

The ShareLink view is designed to share any type of data. In this chapter, we will show you how to use ShareLink to let users share text, URLs, and images.

Let's begin with an example. Assuming you've created a new Xcode project, you can create a share link for sharing a URL by writing the code like this:

struct ContentView: View {
    private let url = URL(string: "https://www.appcoda.com")!

    var body: some View {
        VStack {
            ShareLink(item: url)
        }
    }
}

SwiftUI automatically renders a Share button with a small icon.

Figure 1. The share button
Figure 1. The share button

When tapped, iOS brings up a share sheet for users to perform further actions such as copy and adding the link to Reminders.

Figure 2. Displaying the share sheet
Figure 2. Displaying the share sheet

To share text, instead of URL, you can simply pass the a string to the item parameter.

ShareLink(item: "Check out this new feature on iOS 16")

To customize the appearance of the link, you can provide the view content in the closure like this:

ShareLink(item: url) {
    Image(systemName: "square.and.arrow.up")
}

In this case, SwiftUI only displays the share icon for the link.

Figure 3. Customizing the share button
Figure 3. Customizing the share button

Alternatively, you can present a label with a system image or custom image:

ShareLink(item: url) {
    Label("Tap me to share", systemImage:  "square.and.arrow.up")
}

To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.

results matching ""

    No results matching ""