Hello everyone, I am a beginner in programming and recently encountered an interesting issue in SwiftUI. (I must admit that it might not be a bug and could simply be due to my lack of understanding.)
I have extracted the relevant code that causes this behavior. Here's the code:
struct BugView: View {
var body: some View {
List {
VStack {
Button("Bug") {
print("1")
}
Button("Bug") {
print("2")
}
Button("Bug") {
print("3")
}
}
}
}
}
In this view, clicking any of the buttons results in all of them being triggered simultaneously. As a result, the console outputs:
1
2
3
I would appreciate it if someone could help me understand why this happens and how to fix it. Thanks in advance!
Confirm what darkpaw said.
Whenever you have multiple buttons in a list row, you need to manually set the button style to .borderless or .plain . This is because buttons “adapt” to their context. According to the documentation: So when your button is in a List, its tap target extends to fill the row and you get a highlight animation. SwiftUI isn’t smart enough to stop this side effect when you have more than 2 buttons, so you need to set buttonStyle manually.
.buttonStyle(.borderless)
Get details here