[英]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.