I have to change background color of one of the views. By default they are gray.
It depends on given value. If given value is equal to one of the key value it has to change its background color. My problem is that it changes two views. How can I identify which view it should change?
let numbers = ["200": "299000", "100": "329000"]
@State var selected: Bool = false
var body: some View {
VStack(spacing: 20) {
HStack(spacing: 20) {
ForEach(numbers.sorted(by: <), id: \.key) { key, value in
VStack(alignment: .leading) {
Text(key)
Text(value)
}
.padding()
.background(selected ? Color.red : Color.gray)
.cornerRadius(10)
}
}
setValue(value: 150)
}
.onAppear {
checkValue(value: 150)
}
}
func setValue(value: Int) -> some View {
Text("\(value)")
}
func checkValue(value: Int) {
for price in numbers.keys {
if value >= Int(price) ?? 0 {
selected = true
}
}
}