0
votes

I have a button called "save" that saves the user inputs. But, I want to make it like, if the user tap on Button "Save", then the screen automatically goes back to the previous view. Can I do that by just adding a code to an action in Button? or do I have to use NavigationLink instead of Button?

 Button(action: {
                let title = shortcutTitle
                currentShortcutTitle = title
                UserDefaults.standard.set(title, forKey: "title")
            }, label: {
                Text("Save")
                    .padding()
                    .frame(width: 120, height: 80)
                    .border(Color.black)
            }) //: Button - save
1

1 Answers

1
votes

If you're just trying to go back to the previous view and already inside a NavigationView stack, you can use @Environment(\.presentationMode):

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            NavigationLink(destination: Screen2()) {
                Text("Go to screen 2")
            }
        }.navigationViewStyle(StackNavigationViewStyle())
    }
}

struct Screen2 : View {
    @Environment(\.presentationMode) var presentationMode  //<-- Here

    var body: some View {
        Button("Dismiss") {
            presentationMode.wrappedValue.dismiss() //<-- Here
        }
    }
}