如何从内部的 SwiftUI 视图返回到 UIKit?

How to go back from a SwiftUI View inside a to UIKit?

我在 HostingViewController 和 UIKit Viewcontroller 中有一个 SwiftUI。我的目标是通过按下按钮在它们之间切换。问题是我无法从 HostingViewController 中的 SwiftUI View 返回到 UIKit。

我可以使用这个 segue 函数通过我的 UIKit ViewController 转到托管ViewController:

 @IBSegueAction func swiftUIAction(_ coder: NSCoder) -> UIViewController? {
        return UIHostingController(coder: coder, rootView: WorkoutSelectView())
    }

我试过的

可是我不知道怎么回去。我使用了一个解决方案,我在这里从我的 SwiftUI 视图的 AppDelegate 调用一个函数:

 guard let appDelegate: AppDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
 appDelegate.switchBack()

在 Appdelegate 中我有这个功能:

 func switchBack(){
        guard var rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController else {
                  return
        }
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "Home") as! HomeViewController
        rootViewController.present(controller, animated: true, completion: { () -> Void in
        
        })
    }

这很酷,但问题是:

<WorkoutTracker.HomeViewController: 0x148f072a0>) whose view is not in the window hierarchy.

那么你有什么想法吗?

可能的方法是将完成回调传递到您的 SwiftUI 视图中,如下面的简化演示

struct WorkoutSelectView: View {
    var completion: () -> () = {}

    var body: some View {
        Button("Close", action: completion)
    }
}

并在您的 UIViewController 中使用此回调来关闭呈现的控制器,例如

@IBSegueAction func swiftUIAction(_ coder: NSCoder) -> UIViewController? {
   let controller =  UIHostingController(coder: coder, 
        rootView: WorkoutSelectView() { [weak self] in
           self?.dismiss(true)
        })
   return controller
}