在UIViewControllerSwift 的正常情况下,我使用此代码发送邮件。
UIViewController
let mailComposeViewController = configuredMailComposeViewController() mailComposeViewController.navigationItem.leftBarButtonItem?.style = .plain mailComposeViewController.navigationItem.rightBarButtonItem?.style = .plain mailComposeViewController.navigationBar.tintColor = UIColor.white if MFMailComposeViewController.canSendMail() { self.present(mailComposeViewController, animated: true, completion: nil) } else { self.showSendMailErrorAlert() }
如何在SwiftUI中实现相同目标?
我需要使用UIViewControllerRepresentable吗?
UIViewControllerRepresentable
如前所述,您需要将组件移植到SwiftUIvia UIViewControllerRepresentable。
SwiftUI
这是一个简单的实现:
struct MailView: UIViewControllerRepresentable { @Binding var isShowing: Bool @Binding var result: Result<MFMailComposeResult, Error>? class Coordinator: NSObject, MFMailComposeViewControllerDelegate { @Binding var isShowing: Bool @Binding var result: Result<MFMailComposeResult, Error>? init(isShowing: Binding<Bool>, result: Binding<Result<MFMailComposeResult, Error>?>) { _isShowing = isShowing _result = result } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { defer { isShowing = false } guard error == nil else { self.result = .failure(error!) return } self.result = .success(result) } } func makeCoordinator() -> Coordinator { return Coordinator(isShowing: $isShowing, result: $result) } func makeUIViewController(context: UIViewControllerRepresentableContext<MailView>) -> MFMailComposeViewController { let vc = MFMailComposeViewController() vc.mailComposeDelegate = context.coordinator return vc } func updateUIViewController(_ uiViewController: MFMailComposeViewController, context: UIViewControllerRepresentableContext<MailView>) { } }
用法 :
struct ContentView: View { @State var result: Result<MFMailComposeResult, Error>? = nil @State var isShowingMailView = false var body: some View { VStack { if MFMailComposeViewController.canSendMail() { Button("Show mail view") { self.isShowingMailView.toggle() } } else { Text("Can't send emails from this device") } if result != nil { Text("Result: \(String(describing: result))") .lineLimit(nil) } } .sheet(isPresented: $isShowingMailView) { MailView(isShowing: self.$isShowingMailView, result: self.$result) } } }
(在运行iOS 13的iPhone 7 Plus上进行了测试-就像一个护身符)
为Xcode 11.4更新