You don't need to use ZStack if you have a List, as you simply hide the scroll content background, and set the background colour.
Your original code didn't really make much sense. You were creating three instances of ScreenColorButtons and setting a @State var in each one, which only applies to that particular instance. You never actually linked the colour of the background with any of the buttons.
The following code works. It creates a @State var in the main view containing the buttons, and a @Binding var in the buttons themselves so when you click the button the bound var is updated.
import SwiftUI
struct ContentView: View {
@State private var colorSelected: Color = Color.red
var body: some View {
List {
ScreenColorButtons(colorSelected: $colorSelected, text: "Red", color: .red)
ScreenColorButtons(colorSelected: $colorSelected, text: "Green", color: .green)
ScreenColorButtons(colorSelected: $colorSelected, text: "Blue", color: .blue)
ScreenColorButtons(colorSelected: $colorSelected, text: "Yellow", color: .yellow)
ScreenColorButtons(colorSelected: $colorSelected, text: "Pink", color: .pink)
ScreenColorButtons(colorSelected: $colorSelected, text: "White", color: .white)
ScreenColorButtons(colorSelected: $colorSelected, text: "Gray", color: .gray)
ScreenColorButtons(colorSelected: $colorSelected, text: "Black", color: .black)
}
.background(colorSelected)
.scrollContentBackground(.hidden)
}
}
struct ScreenColorButtons: View {
@Binding var colorSelected: Color
var text: String
var color: Color
var body: some View{
Button(action: {
colorSelected = color
print(colorSelected)
}, label: {
Text(text)
})
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}