首页 > 解决方案 > 当我更改 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))
                }

...

知道问题是什么吗?

编辑:

如果我将ContentViewView 更改为 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)

标签: iosswiftswiftui

解决方案


HomeView自己调用,导致无限循环。


推荐阅读