在 SwiftUI 应用程序中,我想使用共享表打印图像。在下面的代码表中打开空白总是显示没有图像。
import SwiftUI
struct ActivityViewController: UIViewControllerRepresentable {
var activityItems: [Any]
var applicationActivities: [UIActivity]? = nil
func makeUIViewController(context: UIViewControllerRepresentableContext<ActivityViewController>) -> UIActivityViewController {
return UIActivityViewController(activityItems: activityItems, applicationActivities: applicationActivities)
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: UIViewControllerRepresentableContext<ActivityViewController>) {}
}
struct ContentView: View {
@State private var showingShareSheet = false
@State private var snapshotImage: UIImage?
var body: some View {
NavigationStack {
Text("Hello, World!")
VStack {
Button(action: {
self.snapshotImage = UIImage(named: "profile")
if self.snapshotImage != nil {
self.showingShareSheet = true
} else {
print("Image not found")
}
}, label: {
Text("Print")
})
}
.sheet(isPresented: $showingShareSheet) {
if let image = snapshotImage {
ActivityViewController(activityItems: [image])
} else {
Text("No image to share")
}
}
.onAppear {
self.snapshotImage = UIImage(named: "profile")
if self.snapshotImage == nil {
print("Image not found")
}
}
}
}
}
#Preview {
ContentView()
}
Adding hidden image view with opacity 0 fixed the issue.
import SwiftUI
struct ActivityViewController: UIViewControllerRepresentable {
var activityItems: [Any]
var applicationActivities: [UIActivity]? = nil
func makeUIViewController(context: UIViewControllerRepresentableContext<ActivityViewController>) -> UIActivityViewController {
return UIActivityViewController(activityItems: activityItems, applicationActivities: applicationActivities)
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: UIViewControllerRepresentableContext<ActivityViewController>) {}
}
struct ContentView: View {
@State private var showingShareSheet = false
@State private var snapshotImage: UIImage?
var body: some View {
NavigationStack {
Text("Hello, World!")
VStack {
Image(uiImage: snapshotImage ?? UIImage())
.opacity(0)
Button(action: {
self.snapshotImage = UIImage(named: "profile")
if self.snapshotImage != nil {
self.showingShareSheet = true
} else {
print("Image not found")
}
}, label: {
Text("Print")
})
}
.sheet(isPresented: $showingShareSheet) {
if let image = snapshotImage {
ActivityViewController(activityItems: [image])
} else {
Text("No image to share")
}
}
.onAppear {
self.snapshotImage = UIImage(named: "profile")
if self.snapshotImage == nil {
print("Image not found")
}
}
}
}
}
#Preview {
ContentView()
}