I have View A:
struct Dummy: View {
var body: some View {
NavigationStack{
NavigationLink(destination: ViewB()) {
Image(systemName: "gear") // placeholder systemname
.padding()
.background(.ultraThinMaterial)
.clipShape(.circle)
}
.navigationTitle("Home")
}
}
}
and View B in which there’s a text field with the binding value set to “” (empty string):
struct ViewB: View {
@State private var name: String = ""
var body: some View {
NavigationStack {
VStack {
Text("Your name is (name)")
.font(.title)
.padding()
Divider()
TextField("Name", text: $name)
.textFieldStyle(.roundedBorder)
.padding()
}
}
}
}
What I want to do is to prevent the user from going back to View A by pressing the back button on the navigation bar only when the binding value name
is empty. When the user starts typing so the value changes and gets set to something the back button can be pressed again to go back.
I looked for a solution but found nothing.
I’ve tried using the .navigationBarBackButtonHidden()
modifier but it only accepts a Bool and not a Binding<Bool>.