iOSã§ç»åãããã¹ããªã©ãä»ã®ã¢ããªã¸ã·ã§ã¢ããã¨ãã«ã¯ UIActivityViewController
ãå©ç¨ãããSwiftUIã§ã UIActivityViewControllerã使ã£ã¦ç»åãå
±æããå¦çãç´¹ä»ããã
å®è¡ç°å¢
- Xcode 11.6
- iOS 13.6
UIActivityViewControllerã使ã£ã¦ç»åãå ±æãã
SwiftUIã§UIActivityViewControllerã使ãããã®ããªãã¸ã¯ã©ã¹ãä½æãã¾ããä»åã¯ç»åã ããå ±æãããã¨ãæ³å®ãã¦ãã¾ãã
import SwiftUI public struct ShareActivityView: UIViewControllerRepresentable { private let images: [UIImage] private let onCanceled: () -> Void private let onShared: () -> Void public init(images: [UIImage], onCanceled: @escaping () -> Void, success onShared: @escaping () -> Void) { self.images = images self.onCanceled = onCanceled self.onShared = onShared } public func makeUIViewController(context: Context) -> UIActivityViewController { let activityController = UIActivityViewController(activityItems: images, applicationActivities: nil) activityController.completionWithItemsHandler = { (activityType, completed, returnedItems, error) in if !completed { self.onCanceled() return } self.onShared() } return activityController } public func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) { } }
ãã¨ã¯SwiftUIã®ç»é¢å´ã§ã·ã¼ãã« ShareActivityView
ã表示ããã ãã§ãï¼
import SwiftUI struct SampleActivityView : View { @State private var sheetIsPresented = false var body: some View { VStack { Button(action: { self.sheetIsPresented = true }, label: { Text("show activity controller") }) } .sheet(isPresented: $sheetIsPresented) { ShareActivityView(images: [ R.image.dummy_red()!, R.image.dummy_green()!], onCanceled: { // on cancel }) { // on success } } } } struct SampleActivityView_Previews: PreviewProvider { static var previews: some View { SampleActivityView() } }