【发布时间】:2020-06-04 07:41:33
【问题描述】:
我想在用户单击按钮时登录。当他们点击按钮时,它会调用self.auth.login(),这会将loggedIn 更改为true。
发生此更改时,ContentView 将重新加载 HomeView() 作为正文 View。但是它只会使应用程序崩溃。
这是我的代码:
ContentView.swift
struct ContentView: View {
@EnvironmentObject var settings: UserSettings
@EnvironmentObject var auth: UserAuth
var body: some View {
if (!auth.loggedIn){
return AnyView(LoginView())
} else {
return AnyView(HomeView())
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(UserAuth())
}
}
class UserAuth: ObservableObject {
@Published var loggedIn: Bool = false
func login(){
self.loggedIn = true
}
}
struct LoginView: View {
@EnvironmentObject var auth: UserAuth
var body: some View {
ZStack {
Color.orange
.edgesIgnoringSafeArea(.all)
VStack {
Image("launcher_logo").resizable()
.scaledToFit()
.frame(height: 100)
.padding(.top, 100)
Spacer()
Button(action: {
self.auth.login()
print("loggedIn: ", self.auth.loggedIn) // prints "loggedIn: true" then doesn't print again when pressed
}) {
Text(String(auth.loggedIn))
}
...
知道问题出在哪里吗?
编辑:
如果我将 ContentView 视图更改为 LoginView(),那么它不会冻结。该应用程序有效。但我希望 ContentView 根据用户是否登录是动态的。
EDIT2:HomeView 导致它崩溃:
struct HomeView: View {
// @EnvironmentObject var auth: UserAuth
var body: some View {
TabView {
HomeView()
.tabItem {
Image(systemName: "1.square.fill")
Text(String("4"))
}.onTapGesture {
// self.auth.login()
}
HomeView()
.tabItem {
Image(systemName: "3.square.fill")
}
Text("The Last Tab")
.tabItem {
Image(systemName: "3.square.fill")
Text("Profile")
}
}
.font(.headline)
}
func goOnline(){
print("went online")
}
}
控制台日志:
[Firebase/Crashlytics][I-CLS000000] Failed to download settings Error Domain=FIRCLSNetworkError Code=-5 "(null)" UserInfo={status_code=404, type=2, request_id=, content_type=text/html; charset=utf-8}
2020-06-04 19:53:04.408869+1000 App[6718:4035694] Connection 5: received failure notification
2020-06-04 19:53:04.409001+1000 App[6718:4035694] Connection 5: failed to connect 3:-9816, reason -1
2020-06-04 19:53:04.409111+1000 App[6718:4035694] Connection 5: encountered error(3:-9816)
【问题讨论】:
-
您是否将
UserSettings添加到您的环境中? (environmentObject)。在预览中,您只添加两个必需的环境对象之一。 -
什么是崩溃信息?
-
没有崩溃信息。它只是冻结。控制台最后的输出是
loggedIn: true -
如果我将
ContentView视图更改为LoginView(),那么它不会冻结。该应用程序有效。