如何从 SwiftUI 视图中返回到 UIKit? [英] How to go back from a SwiftUI View inside a to UIKit?

查看:46
本文介绍了如何从 SwiftUI 视图中返回到 UIKit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a SwiftUI inside a HostingViewController and a UIKit Viewcontroller. My goal is to switch between them with a button press. The problem is I cannot achieve to go from my SwiftUI View inside the HostingViewController back to UIKit.

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

I can go to the HostingViewController over my UIKit ViewController with this segue function:

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

我的尝试

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

But I do not know how to go back. I have used a solution where I call a function from my AppDelegate of my SwiftUI View here:

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

在 Appdelegate 里面我有这个功能:

and inside the Appdelegate I have this function:

 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
        
        })
    }

很酷的事情是它有效,但问题是:

The cool thing about this it works but the problem is then:

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

所以你有什么想法吗?

推荐答案

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

The possible approach is to pass completion callback into your SwiftUI view, like in below simplified demo

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

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

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

and use this callback in your UIViewController to dismiss presented controller, like

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

这篇关于如何从 SwiftUI 视图中返回到 UIKit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆