Ask Your Question
1

The log out function in my app functions properly when placed inside a button within the main view, but fails to work when accessed from a .sheet.

asked 2023-07-17 02:52:23 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-17 03:07:01 +0000

lakamha gravatar image

This may be because the .sheet view is not connected to the main view's session. To fix this issue, you can pass a binding or an environment object to the .sheet view, which contains information about the user's session. You can then use this information to log out the user.

Here's an example of passing a binding to the .sheet view:

struct ContentView: View {
    @State private var isLoggedIn = false
    @State private var showSheet = false

    var body: some View {
        VStack {
            if isLoggedIn {
                Text("App content")
            } else {
                Button("Log in", action: { isLoggedIn = true })
            }
            Button("Log out", action: { isLoggedIn = false })
                .sheet(isPresented: $showSheet, content: {
                    LogoutView(isLoggedIn: $isLoggedIn)
                })
            Button("Show sheet", action: { showSheet = true })
        }
    }
}

struct LogoutView: View {
    @Binding var isLoggedIn: Bool

    var body: some View {
        VStack {
            Text("Are you sure you want to log out?")
            Button("Log out", action: { isLoggedIn = false })
        }
    }
}

In this example, we have a ContentView that contains a button to log out the user, and a button to show a .sheet view. The .sheet view shows a LogoutView, which contains a button to log out the user.

To pass the isLoggedIn state to the LogoutView, we declare it as a @Binding in the LogoutView and pass it as a parameter to the view's initializer. We then use this binding to update the isLoggedIn state in the ContentView when the user logs out.

By using a binding, we ensure that the LogoutView is connected to the ContentView's session, and the log out function works as expected.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-17 02:52:23 +0000

Seen: 9 times

Last updated: Jul 17 '23