此代码在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”
答案 0 :(得分:1)
您可以使用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")
}
}
}