问题描述
我在从 MainView 开始的所有视图中都使用 SwiftUI 1.0,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)。
解决方法
可能的解决方案是使用回调如
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()
}