Ios 如何从到UIKit中的SwiftUI视图返回?
我在HostingViewController和UIKit Viewcontroller中有一个SwiftUI。我的目标是通过按下按钮在它们之间切换。问题是我无法实现从HostingViewController内的SwiftUI视图返回UIKit 我可以通过以下segue功能通过我的UIKit ViewController转到HostingViewController:Ios 如何从到UIKit中的SwiftUI视图返回?,ios,swift,swiftui,uikit,appdelegate,Ios,Swift,Swiftui,Uikit,Appdelegate,我在HostingViewController和UIKit Viewcontroller中有一个SwiftUI。我的目标是通过按下按钮在它们之间切换。问题是我无法实现从HostingViewController内的SwiftUI视图返回UIKit 我可以通过以下segue功能通过我的UIKit ViewController转到HostingViewController: @IBSegueAction func swiftUIAction(_ coder: NSCoder) -> UIVi
@IBSegueAction func swiftUIAction(_ coder: NSCoder) -> UIViewController? {
return UIHostingController(coder: coder, rootView: WorkoutSelectView())
}
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
})
}
我尝试过的
但我不知道如何回去。我使用了一种解决方案,在这里,我从SwiftUI视图的AppDelegate调用函数:
guard let appDelegate: AppDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
appDelegate.switchBack()
在Appdelegate中,我有一个函数:
@IBSegueAction func swiftUIAction(_ coder: NSCoder) -> UIViewController? {
return UIHostingController(coder: coder, rootView: WorkoutSelectView())
}
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
}