powerbee
(Brian Elkin)
1
I am having trouble understanding the execution in a View. Given the code below.
This is just a form which asks for a name and then has 2 buttons, one for cancel and one for save. When I run this view and hit the cancel button, the console returns:
in cancel
in save
When I hit the save button, I get the same console output:
in cancel
in save
What am I missing here? I want each button to just run the corresponding code to the button pressed.
Thanks so much for any help.
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()
}
}
}
}
powerbee
(Brian Elkin)
2
Someone in another forum was able to help me. Since I am using a Form which is a List, you need to include a button style, because currently the entire HStack reacts to each tap.
So the code needs .buttonStyle(BorderlessButtonStyle()) to be added to each button:
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())
}
}
}
Here is more information on this issue.
h t t p s : / / w w w.hackingwithswift.com/forums/swiftui/button-s-on-click-event-being-applied-to-hstack-surrounding-it/2859