Reputation: 11
I need to modify the share sheet functionality in my SwiftUI app. I am looking to add a custom button to the share sheet interface. However, I'm facing some challenges in implementing this feature.
Could someone kindly provide guidance or share insights on how to achieve this?
Upvotes: 0
Views: 1350
Reputation: 1900
add "Action Extension" to your project.
in the targets list press "+" and search for "Action Extension"
then add rules to info.plist to handle necessary types
Upvotes: 0
Reputation: 89
import SwiftUI
import UIKit
Create a Share Button: Add a share button to your SwiftUI view. This button will trigger the share sheet when tapped.
struct ContentView: View {
var body: some View {
Button(action: {
// Code to share content
shareContent()
}) {
Text("Share")
}
}
func shareContent() {
let textToShare = "Check out this awesome content!"
let itemsToShare = [textToShare] // Add more items if needed (e.g., URLs, images)
let activityViewController = UIActivityViewController(activityItems: itemsToShare, applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(activityViewController, animated: true, completion: nil)
}
}
You can customize the sharing options by adding more items to itemsToShare. For example, if you want to share an image, you can include the image data in itemsToShare.
let imageToShare = UIImage(named: "your_image_name")
let itemsToShare: [Any] = [textToShare, imageToShare]
Run your app and tap the "Share" button to see the share sheet with the content you specified.
Upvotes: 0
Reputation: 2197
import SwiftUI
struct ContentView: View {
@State private var isShareSheetPresented = false
var body: some View {
Button(action: {
self.isShareSheetPresented.toggle()
}) {
Text("Share")
}
.sheet(isPresented: $isShareSheetPresented, content: {
// Custom Share Sheet
ShareSheet(activityItems: ["Hello, world!"])
})
}
}
struct ShareSheet: View {
var activityItems: [Any]
var body: some View {
VStack {
Text("Share")
.font(.title)
.padding()
Button(action: {
// Handle your custom action
print("Custom action tapped")
}) {
Text("Custom Action")
}
.padding()
Divider()
Button(action: {
// Share functionality
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(activityViewController, animated: true, completion: nil)
}) {
Text("Share")
.foregroundColor(.blue)
}
.padding()
Spacer()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Upvotes: 0