在 SwiftUI 中以编程方式打开 ShareLink

Har*_*hIT 9 swift swiftui swiftui-sharelink

使用ShareLink会显示“共享”按钮,因此当用户点击该按钮时,它会打开“共享”弹出窗口。

ShareLink(item: data, subject: Text("Subject"), message: Text("Message"))
Run Code Online (Sandbox Code Playgroud)

我想以编程方式截屏,然后在共享弹出窗口上共享。当用户点击 ShareLink 按钮或以编程方式打开 SharePopup 时,有什么方法可以执行操作,就像我们以前在 Swift 中作为 UIActivityController 所做的那样?

Ash*_*lls 7

您可以通过将 aUIActivityController包裹起来来做到这一点UIViewControllerRepresentable

在此示例中,我UIImage通过单击按钮创建一个,然后根据需要通过ImageWrapper以下方式共享它:sheetitem:Identifiable

struct ImageWrapper: Identifiable {
    let id = UUID()
    let image: UIImage
}

struct ContentView: View {
    
    @State private var imageWrapper: ImageWrapper?
    
    var body: some View {
        Button {
            // Use your UIImage here
            self.imageWrapper = ImageWrapper(image: UIImage())
        } label: {
            Label("Share", systemImage: "square.and.arrow.up")
        }
        .sheet(item: $imageWrapper, onDismiss: {
            
        }, content: { image in
            ActivityViewController(imageWrapper: image)
        })
    }
}

struct ActivityViewController: UIViewControllerRepresentable {
    let imageWrapper: ImageWrapper
    func makeUIViewController(context: Context) -> UIActivityViewController {
        UIActivityViewController(activityItems: [imageWrapper.image], applicationActivities: nil)
    }
    
    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {
    }
}
struct ContentView_Previews: PreviewProvider {
    
    static var previews: some View {
        ContentView()
    }
}
Run Code Online (Sandbox Code Playgroud)