I have two buttons defined inside a Form. Pressing either one activates both. This doesn’t happen if I remove the Form or the HStack. I opened a Feedback for this, but haven’t gotten a response yet. I haven’t been able to find a workaround for this while keeping the Form and the HStack.
Any thoughts?
import SwiftUI
struct ContentView: View
{
var body: some View
{
Form
{
HStack
{
Button("Button 1")
{ let _ = print("Button 1 tapped") }
Button("Button 2")
{ let _ = print("Button 2 tapped") }
}
}
}
}
Add .buttonStyle(BorderedButtonStyle())
to each Button or add one instance of the modifier to the HStack. Either way that will work.
Like so:
struct ContentView: View {
var body: some View {
Form {
HStack {
Button("Button 1") {
let _ = print("Button 1 tapped")
}
.buttonStyle(BorderedButtonStyle())
Button("Button 2") {
let _ = print("Button 2 tapped")
}
.buttonStyle(BorderedButtonStyle())
}
}
}
}
or if you prefer:
struct ContentView: View {
var body: some View {
Form {
HStack {
Button("Button 1") {
let _ = print("Button 1 tapped")
}
.buttonStyle(.bordered)
Button("Button 2") {
let _ = print("Button 2 tapped")
}
.buttonStyle(.bordered)
}
}
}
}
Excellent! It also works with .plain
, which is what I wanted, Thank you.
Any idea why that fixes the problem? Is it an Xcode bug?
I don’t know why the modifier makes the Buttons work independently. The solution I provided was from a post on Stackoverflow. Is it a bug? Don’t know.
This has been reported several times before, including the one that Chris referenced from December 2019. I opened a feedback (FB16542790) on February 21, but it’s not likely to get any attention because there have been no recent similar reports. If anyone cares, opening more feedbacks for the same problem might get some action.