简体   繁体   中英

I am using NavigationLink to navigate between views and it doesn't work in a single view in SwiftUI

When I want to log out of my app I want to show the initial view that has the "log in" / "create account" page using the NavigationLink. I used the exact same method in other places of the app and it works there, but here it doesn't. Here is my code:

import SwiftUI

var signOut = false

struct SignOut: View {

    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    @State private var curent: Int? = nil

    var body: some View {
        VStack {
            NavigationLink(destination: ContentView(), tag: 1, selection: $curent) {
                EmptyView()
            }.buttonStyle(PlainButtonStyle())

            Button(action: {
                let defaults = UserDefaults.standard
                defaults.set(false, forKey: "isLoggedIn")
                defaults.set("", forKey: "token")

                if contentViewVerify
                {
                    print("content true")
                    self.presentationMode.wrappedValue.dismiss()
                }
                else if contentViewVerify == false
                {
                    print("content false")
                    self.curent = 1 // if contentViewVerify is false I want to use the NavigationLink method which activates once curent = 1
                }

            }) {
                Text("SignOut")
            }.navigationBarTitle("covid")
            .navigationBarBackButtonHidden(true)
            .onAppear(perform: {
                signOut = true
            })
        }
    }
}

struct SignOut_Previews: PreviewProvider {
    static var previews: some View {
        SignOut()
    }
}

Thank you in advance!

NavigationLink works only in NavigationView , so it should be somewhere like

struct SignOut_Previews: PreviewProvider {
    static var previews: some View {
       NavigationView {       // for testing in preview
           SignOut()
       }
    }
}

Note: contentViewVerify changing is absent in presented code, make sure it is really set to false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM