簡體   English   中英

如何從 SwiftUI 查看 UIKit 內部的 go?

[英]How to go back from a SwiftUI View inside a to UIKit?

我在 HostingViewController 和 UIKit Viewcontroller 中有一個 SwiftUI。 我的目標是通過按下按鈕在它們之間切換。 問題是我無法從 HostingViewController 內的 SwiftUI 視圖返回到 UIKit 中的 go。

我可以使用此segue function 通過我的 UIKit ViewController 將 go 連接到 HostingViewController:

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

我試過的

但是不知道go怎么回。 我使用了一個解決方案,我從我的 SwiftUI 的 AppDelegate 調用 function 在此處查看:

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

在 Appdelegate 里面我有這個 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
        
        })
    }

很酷的事情是它可以工作,但問題是:

<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 中使用此回調來關閉呈現的 controller,例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM