[英]How to do navigation control in SwiftUI view
此代碼在UIViewController
內工作正常:
let hostingController = UIHostingController(rootView: homeMainView())
self.navigationController?.pushViewController(hostingController, animated: true)
但現在我想在 SwiftUI 中使用它 以這種方式查看:
struct AppRootView: View {
var body: some View {
VStack(alignment: .leading) {
Text("App").bold()
.font(.largeTitle)
}.onAppear(perform: handleSignIn)
.frame(minWidth: 0,
maxWidth: .infinity,
minHeight: 0,
maxHeight: .infinity).background(Color.yellow)
}
func handleSignIn() {
if let _ = app.currentUser() {
print("user is logged in")
let hostingController = UIHostingController(rootView: homeMainView())
self.navigationController?.pushViewController(hostingController, animated: true)
} else {
print("not logged in; present sign in/signup view")
}
}
}
在 SwiftUI 視圖中啟動新視圖的最佳方式是什么?
上面的代碼拋出一個錯誤:
“AppRootView”類型的值沒有成員“navigationController”
您可以使用NavigationLink
呈現您的視圖。
在后台添加一個空的NavigationLink
並設置isLinkActive
如果用戶已登錄。您還需要將其全部包裝在NavigationView
中:
struct AppRootView: View {
@State var isLinkActive = false // <- add here
var body: some View {
NavigationView { // <- wrap in the `NavigationView`
VStack(alignment: .leading) {
Text("App")
.bold()
.font(.largeTitle)
}
.navigationBarTitle("", displayMode: .inline) // optionally set title
.navigationBarHidden(true)
.background( // add a hidden `NavigationLink` in the background
NavigationLink(destination: homeMainView(), isActive: $isLinkActive) {
EmptyView()
}
.hidden()
)
}
.onAppear(perform: handleSignIn)
.frame(minWidth: 0,
maxWidth: .infinity,
minHeight: 0,
maxHeight: .infinity).background(Color.yellow)
}
func handleSignIn() {
if let _ = app.currentUser() {
isLinkActive = true // <- activate the `NavigationLink`
} else {
print("not logged in; present sign in/signup view")
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.