Pat*_*els 7 ios swift ios-sharesheet swiftui
按照几个教程(例如 Medium),您可以打开一个共享表,如下所示:
Button(action: {
let url = URL(string: "https://apple.com")
let av = UIActivityViewController(activityItems: [url!], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)
}) {
Text("Share Me")
}
Run Code Online (Sandbox Code Playgroud)
但是,这在所呈现的工作表中不起作用。
BaseView,包含工作共享表和打开表的代码示例:
struct BaseView: View {
...
@State var isSheetViewShowing = false
...
var body: some View {
// Open sheet view where share sheet does not work.
Button(action: {
isSheetViewShowing.toggle()
}) {
Text("Show sheet view")
}
Text("")
.frame(width: 0, height: 0)
.sheet(isPresented: $isSheetViewShowing) {
SheetView(showSheetView: $isSheetViewShowing)
}
// Below share Sheet works!
Button(action: {
let url = URL(string: "https://apple.com")
let av = UIActivityViewController(activityItems: [url!], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)
}) {
Text("Share Me")
}
}
}
Run Code Online (Sandbox Code Playgroud)
打开SheetView,相同的代码不起作用:
struct SheetView: View {
...
@Binding var showSheetView: Bool
...
var body: some View {
// Below share Sheet does not work anymore!
Button(action: {
let url = URL(string: "https://apple.com")
let av = UIActivityViewController(activityItems: [url!], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)
}) {
Text("Share Me")
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何实现从工作表视图中显示共享工作表?共享某些内容的意图是否必须传递给 BaseView(和/或 SheetView 是否必须关闭),然后从那里调用共享表?(我希望直接从 SheetView 获得解决方案)
Asp*_*eri 10
问题在于试图显示根控制器的第二张表。它已经附加了一个,因此拒绝另一个(在本例中是“活动”)。
解决方案是使用自己的控制器,放置在打开的工作表中作为活动的演示者。
这是一个简单的演示。使用 Xcode 13 / iOS 15 进行测试。
struct SheetView: View {
@Binding var showSheetView: Bool
@State private var isShare = false
var body: some View {
// Below share Sheet - now works!
Button(action: {
isShare = true // present activity
}) {
Text("Share Me")
}
.background(SharingViewController(isPresenting: $isShare) {
let url = URL(string: "https://apple.com")
let av = UIActivityViewController(activityItems: [url!], applicationActivities: nil)
// For iPad
if UIDevice.current.userInterfaceIdiom == .pad {
av.popoverPresentationController?.sourceView = UIView()
}
av.completionWithItemsHandler = { _, _, _, _ in
isShare = false // required for re-open !!!
}
return av
})
}
}
struct SharingViewController: UIViewControllerRepresentable {
@Binding var isPresenting: Bool
var content: () -> UIViewController
func makeUIViewController(context: Context) -> UIViewController {
UIViewController()
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
if isPresenting {
uiViewController.present(content(), animated: true, completion: nil)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5313 次 |
| 最近记录: |