I am fairly new to SwiftUI and am having trouble understanding why the following view / form executes the same code no matter what button is pushed. If I click the cancel button I get on the console.
in cancel
in save
If I click the save button, I get the same thing.
in cancel
in save
I know I am missing something fundamental, but can't sort it out. Any help would be appreciated.
var body: some View {
Form {
TextField("Enter name", text: $personModel.modelName)
HStack {
Button("Cancel") {
print("in cancel")
presentationMode.wrappedValue.dismiss()
}
Spacer()
Button("Save") {
print("in save")
personModel.save()
presentationMode.wrappedValue.dismiss()
}
}
}
}
Change like this:
var body: some View {
Form {
TextField("Enter name", text: $personModel.modelName)
HStack {
Button("Cancel") {
print("in cancel")
presentationMode.wrappedValue.dismiss()
}
.buttonStyle(BorderlessButtonStyle())
Spacer()
Button("Save") {
print("in save")
personModel.save()
presentationMode.wrappedValue.dismiss()
}
.buttonStyle(BorderlessButtonStyle())
}
}
}
Adding .buttonStyle(BorderlessButtonStyle()).
Problem was caused by Form (idem with List) : all the HStack react to tap.
Read here:
h t t p s : / / w w w.hackingwithswift.com/forums/swiftui/button-s-on-click-event-being-applied-to-hstack-surrounding-it/2859