有没有一种方法可以基于SwiftUI中的环境变量来更改视图?

时间:2019-12-10 23:18:40

标签: swift view environment-variables swiftui

我希望能够通过单击一个按钮在SwiftUI中更改视图。我有设置按钮来切换环境变量,如下所示

struct SettingsButton: View {

    @EnvironmentObject var settings: UserSettings

    var body: some View {
        VStack {
            Button(action: { self.settings.settingsView.toggle() }) {
                Image(systemName: "gear")
                    .font(Font.system(size: 25))
                    .frame(width: 25, height: 25)
                    .foregroundColor(.primary)
                    }
                }
                .offset(x: 180, y: -372)}
        }

我也在这里声明了Observable对象

import Foundation
import GoogleSignIn

class UserSettings: ObservableObject {
    @Published var studentID = ""
    @Published var givenName = ""
    @Published var settingsView = false
    @Published var profileView = false
    @Published var isLogged = GIDSignIn.sharedInstance()?.currentUser
}

最后,我在视图中有一个ViewBuilder设置,该设置是在开始时加载的,以侦听变量中的更改并相应地切换视图,但是在加载应用程序并轻按按钮时,应用程序冻结并且保持无响应。

struct Login: View {

    @EnvironmentObject var settings: UserSettings

    @ViewBuilder var body : some View {

        if settings.isLogged != nil {
            MainView()
        }
        else {
            LoginPage()
        }
        if settings.settingsView {
            SettingsView()
        }

    }
}

我想知道是否存在不使用.sheet或导航链接的任何已知方法来进行尝试,非常感谢!

1 个答案:

答案 0 :(得分:0)

在没有看到MainView(), LoginPage() and SettingsView()的情况下,我认为您应该在Login()视图中执行以下操作:

我在您的观点周围添加了VStack

struct Login: View {
    @EnvironmentObject var settings: UserSettings

    @ViewBuilder var body: some View {
        VStack {
            if settings.isLogged != nil {
                MainView()
            } else {
                LoginPage()
            }
            if settings.settingsView {
                SettingsView()
            }
        }
    }
}

由于SceneDelegate被定义为UserSettings(),因此还要确保EnvironmentObject中包含以下内容:

// Create the SwiftUI view that provides the window contents.
let contentView = Login()
    .environmentObject(UserSettings())