该代码在内部可以正常工作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")
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句