繁体   English   中英

如何从 SwiftUI 视图导航回 UIViewController?

[英]How to navigate back to UIViewController from SwiftUI View?

我在所有视图中都使用 SwiftUI 1.0,因为我使用的是通过 UIKit 制作的客户端 LoginSDK,它是主屏幕而不是登录。

因此,在 LoginViewController 中,我可以使用以下代码在成功登录时推送 MainView():

func showMainView() {
    let host = UIHostingController(rootView: MainView())
    self.navigationController?.navigationBar.isHidden = true
    self.navigationController?.pushViewController(host, animated: true)
}

在 MainView 中,我尝试实现一个注销方法,当用户使用以下代码单击注销按钮时,该方法将 LoginViewController 设置为 rootView:

struct MainView: View {
    
    var body: some View {
            NavigationView {
                    VStack {
                        Button(action: {
                           logout()
                        }, label: {
                            Image("Logout")
                                .resizable()
                                .frame(width: 20, height: 16)
                        })
                    }
            }
    }

  //Method to logout and set the RootNavigationViewController as rootViewController
  func logout () {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    //The LoginViewController is embedded in RootNavigationViewController
    let rootViewController = storyboard.instantiateViewController(withIdentifier: "RootNavigationViewController") as! UINavigationController
            
    if let window = UIApplication.shared.windows.first {
        window.rootViewController = rootViewController
        window.endEditing(true)
        window.makeKeyAndVisible()
    }
  }

}

上面的注销方法实现什么也没做。 我想知道如何从 MainView(A SwiftUI 结构)导航回 LoginViewController(A UIKit UIViewController)。

可能的解决方案是使用回调

struct MainView: View {
    var didLogout: () -> ()
    
    // ... other code

  func logout () {
    // ... make logout activity here and on completion perform

    // DispatchQueue.main.async {  << if logout callback in different queue
       didLogout()
    // }
  }
}

现在我们可以将它用作

func showMainView() {
    let host = UIHostingController(rootView: MainView() { [weak self] in
       self?.navigationController?.popViewController(animated: true)  // << here !!
    })

    self.navigationController?.navigationBar.isHidden = true
    self.navigationController?.pushViewController(host, animated: true)
}

这对我来说非常有效,我希望这会有所帮助!

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let rootViewController = storyboard.instantiateViewController(withIdentifier: "YourIdentifier")

           if let window = UIApplication.shared.windows.first {
               window.rootViewController = rootViewController
               window.endEditing(true)
               window.makeKeyAndVisible()
           }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM