ios - 当我更改 EnvironmentObject 值时,应用程序冻结
问题描述
我想在我的用户单击按钮时登录。当他们单击按钮时,它会调用self.auth.login()
which 更改loggedIn
为 true。
当这种变化发生时,ContentView
意味着重新加载HomeView()
as body View
。但是,它只会使应用程序崩溃。
这是我的代码:
内容视图.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
View 更改为 justLoginView()
那么它不会冻结。该应用程序有效。但我希望 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)
解决方案
您HomeView
自己调用,导致无限循环。
推荐阅读
- python - findall 在字符串上的问题(预期的字符串或类似字节的对象)
- javascript - 如何使用 if、else if 和 else 语句来验证两个字符串
- graphql - 如何使用变量更新graphql中的条目
- css - 带 1 个圆边的矩形
- javascript - 我怎样才能找到数组中的平均值
- node.js - 如何在 AWS lambda 上使用 graphql 'isValidJSValue' 或 'coerceValue'?
- facebook - 无法将 Spark AR 效果上传到 Instagram
- javascript - 如何使用 isHidden 仅在移动设备上隐藏项目
- python - 当我尝试从 pycuda 运行模块时,出现错误:“没有名为 'pycuda._driver' 的模块”
- html - 我需要文本随着网站大小的变化而移动(我需要它来响应网站)