Skip to content

Instantly share code, notes, and snippets.

@hoyelam
Created January 26, 2021 19:07
Show Gist options
  • Save hoyelam/04f4d476f6f987ac81ec67cbf5cbc6e7 to your computer and use it in GitHub Desktop.
Save hoyelam/04f4d476f6f987ac81ec67cbf5cbc6e7 to your computer and use it in GitHub Desktop.
Share Sheet UIActivityViewController within SwiftUI
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, world!")
.padding()
.shareSheet(items: ["Hello world!"])
Text("Hello, world!")
.padding()
.shareSheet(items: ["Hello world!"], excludedActivityTypes: [.postToFacebook])
// OR
Text("Hello, world!")
.padding()
.modifier(ShareSheetModifer(shareSheetItems: ["Hello, world!"]))
Text("Hello, world!")
.padding()
.modifier(ShareSheetModifer(shareSheetItems: ["Hello, world!"],
excludedActivityTypes: [.postToFacebook]))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct ShareSheetModifer: ViewModifier {
@State private var showShareSheet: Bool = false
@State var shareSheetItems: [Any] = []
var excludedActivityTypes: [UIActivity.ActivityType]? = nil
func body(content: Content) -> some View {
content
.contextMenu {
Button(action: {
self.showShareSheet.toggle()
}) {
Text("Share")
Image(systemName: "square.and.arrow.up")
}
}
.sheet(isPresented: $showShareSheet, content: {
ActivityViewController(activityItems: self.$shareSheetItems, excludedActivityTypes: excludedActivityTypes)
})
}
}
struct ActivityViewController: UIViewControllerRepresentable {
@Binding var activityItems: [Any]
var excludedActivityTypes: [UIActivity.ActivityType]? = nil
func makeUIViewController(context: UIViewControllerRepresentableContext<ActivityViewController>) -> UIActivityViewController {
let controller = UIActivityViewController(activityItems: activityItems,
applicationActivities: nil)
controller.excludedActivityTypes = excludedActivityTypes
return controller
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: UIViewControllerRepresentableContext<ActivityViewController>) {}
}
extension View {
func shareSheet(items: [Any], excludedActivityTypes: [UIActivity.ActivityType]? = nil) -> some View {
self.modifier(ShareSheetModifer(shareSheetItems: items, excludedActivityTypes: excludedActivityTypes))
}
}
@mrbodich
Copy link

This code is producing bottom safe area spacing. Did you manage to fix that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment