0

我在所有视图中都使用 SwiftUI 1.0,从 MainView 开始,MainView 是除登录之外的主屏幕,因为我使用的是通过 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(一个 SwiftUI 结构)导航回 LoginViewController(一个 UIKit UIViewController)。

4

2 回答 2

0

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

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)
}
于 2021-02-23T04:42:17.497 回答
0

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

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()
           }
于 2021-07-17T16:28:33.620 回答