How to integrate UIActivityViewController with SwiftUI's ScrollView?

前端 未结 1 1741
暖寄归人
暖寄归人 2021-01-19 07:24

In a project I have a ScrollView surrounding a VStack of items which each have a button to trigger the Activity View via the UIActivityViewCo

相关标签:
1条回答
  • 2021-01-19 08:03

    Here is the approach that works (tested with Xcode 11.2/iOS 13.2)... The extra wrapper host controller is not needed, and it is better to use native SwiftUI instruments for presentation.

    import SwiftUI
    
    struct ActivityView: UIViewControllerRepresentable {
        var url: String
        @Binding var showing: Bool
    
        func makeUIViewController(context: Context) -> UIActivityViewController {
            let vc = UIActivityViewController(
                activityItems: [NSURL(string: url)!],
                applicationActivities: nil
            )
            vc.completionWithItemsHandler = { (activityType, completed, returnedItems, error) in
                self.showing = false
            }
            return vc
        }
    
        func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {
        }
    }
    
    struct TestUIActivityView: View {
        @State var showSheet = false
    
        var body: some View {
            ScrollView {
            Group {
                Button(action: {
                    self.showSheet.toggle()
                  }) {
                      Text("Open Activity View")
                  }
                .sheet(isPresented: $showSheet) {
                    ActivityView(url: "https://www.wikipedia.org", showing: self.$showSheet)
                }
            }
        }
        }
    }
    
    struct TestUIActivityView_Previews: PreviewProvider {
        static var previews: some View {
            TestUIActivityView()
        }
    }
    
    0 讨论(0)
提交回复
热议问题